Node Js Promise Inside For Loop Always Prints Promise { }
I'm trying to resolve a promise inside a for-loop in node js. In my code, I have a for loop in which I call a function findincollection that returns a promise. Then I push the data
Solution 1:
What you need here is Promise.all()
. It returns a new promise, which gets resolved once all passed promises get resolved.
You can try something similar to:
var promises = [];
for (y = 0; y < list.length; y++) {
promises.push(findincollection(list[y], mob, savetofile));
}
Promise.all(promises)
.then(dt => {
finalresult.push(dt); //pushes all 3 objects one by oneconsole.log(dt); //prints 3 objects one by one
client.close();
if (y == (collist.length)) {
resolve(finalresult);
}
}); // <-- this will be raised once all your promises are resolved
I see you're closing client inside each promise and this client is not a local variable. So I think you should be closing it after all your promises are completed.
Post a Comment for "Node Js Promise Inside For Loop Always Prints Promise { }"