Ad

How To Wait For Promise To Execute In For-loop Using Node.js?

- 1 answer

I'm using node.js and I have a problem using for-loop and promise. How can I wait for promise.then() before the next step of for-loop?


var array = ["apple", "orange"]

for (var i in array) {
            console.log(array[i])
            var promise = //any promise, doesn't matter now 
            promise.then(function(result) {
               console.log(array[i])
            }) 
            .catch(function() {
               console.log("Promise Rejected");
            });
}

I expect the output to be "apple", "apple", "orange", "orange", but the actual output is "apple", "orange", "orange", "orange"

Ad

Answer

We can use async/await to give us this behaviour. The function testAwait() will return immediately, but we'll await the output of getResult() on each iteration of the loop.

var array = ["apple", "orange"]

// Mock function, could represent an API call etc..
function getResult(arg) { 
    return new Promise(resolve => setTimeout(resolve, 500, arg + "_result"));
}

async function testAwait() {
    for (var i in array) {
        console.log("Loop counter:", i)
        console.log("Input:", array[i])
        // getResult returns a Promise, we'll _await_ it here..
        let result = await getResult(array[i]);
        console.log("Result:", result); 
    }
}

testAwait();

Ad
source: stackoverflow.com
Ad