Here is some code (it's an over-simplified example, I know it is dumb):
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function test() {
[1, 2, 3].map(() => {
console.log('test');
await sleep(1000);
});
}
test();
The objective is to:
test
then wait one secondtest
then wait one secondtest
then wait one secondBut running this code results in a failure:
await is a reserved word
I know I can do fix it by using a for loop:
async function test() {
for(let i = 0; i < 3; i++) {
console.log('test');
await sleep(1000);
}
}
But is there a way to do it in a more "functional" way. I mean, can I avoid the for
loop and await inside a map?
The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in . then() and .
If the functions in your example are synchronous, then adding await has no effect whatsoever. The function is called, and when it returns, execution continues.
The async function declaration defines an asynchronous function, which returns an AsyncFunction object. Async/await is actually built on top of promises. It cannot be used with plain callbacks or node callbacks. The word “async” before a function means one simple thing: a function always returns a promise.
for await...of can only be used in contexts where await can be used, which includes inside an async function body and in a module. Even when the iterable is sync, the loop still awaits the return value for every iteration, leading to slower execution due to repeated promise unwrapping.
const result = await [1, 2, 3].reduce(async function(prom, v){
const result= await prom;
await sleep(1000);
result.push(v);
return result;
}, Promise.resolve([]));
You could reduce to create a promise chain. However in your simplyfied case:
(a=b=>(b==2||(console.log("test"),setTimeout(a,1000,b+1))))(0);
If a library like bluebird is an option then you could write:
'use strict'
const Promise = require('bluebird')
async function test() {
return Promise.mapSeries([1, 2, 3], async (idx) => {
console.log('test: ' + idx);
await Promise.delay(1000)
});
}
test();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With