简体   繁体   中英

Node.js: Async function seems to not wait for resolve of Promise within for loop

For loop ends without any code after the first await new Promise being executed. If I understand correctly, each iteration should pause for 2 seconds before Promise is resolved, console.log ouputs the specified string, and the iteration ends. How should I rewrite the code to make it work as I intended?

'use strict';

(async function () {
    for (let i = 0; i < 5; i++) {
        await new Promise(resolve => { setTimeout(() => { resolve }, 2000) });
        console.log('end of loop');
    }
})();

In your snippet setTimeout will call anonymous function that will evaluate resolve as expression, which return a function. You need to call resolve() explicitly or pass it to setTimeout as first argument of type function .

Change

setTimeout(() => { resolve }, 2000)

to

setTimeout(resolve, 2000)

or

setTimeout(() => { resolve() }, 2000)

You can write this way,

'use strict';

var wait2Sec = function (time = 2000) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => { 
            resolve(); // <--- remamber to call the resolve function
        }, time)
    });
}

(async function () {
    for (let i = 0; i < 5; i++) {
        await wait2Sec();
        console.log('end of loop');
    }
})();

您需要在 setInterval 回调中调用 resolve 函数。

await new Promise(resolve => { setTimeout(() => { resolve() }, 2000) });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM