During my work with mongo, I encountered a need to execute an async call for each item within a loop. My goal is to carry out another command only when all promises within the loop have been fulfilled. However, currently it seems that the promises in the loop are being resolved after the code specified in the 'then' block following the loop.
I am aiming for the sequence to be:
Loop iteration promises then additional code
Instead of the current order which is:
Further code Looped promises
MongoClient.connect(connecturl)
.then((client) => {
databases.forEach((val) => {
val.collection.forEach((valcol) => {
client.db(val.databasename).stats() //(This is the async call)
.then((stats) => {
//Perform actions here based on the collection stats
})
})
})
})
.then(() => {
//Execute this section once all tasks above this point are completed
})
.catch((error) => {
}
Your help in resolving this issue would be greatly appreciated.