I'm trying to wait for a bunch of promises to complete. I know I can do this with Promise.all
, but I can't figure out what to do when one of those promises pushes a new promise into the promise list.
Example:
asyncFunction(...).then(result => {
// do something
});
asyncFunction(...).then(result => {
for(let row of result) {
asyncFunction(row);
}
});
console.log(promises.length); // 2
await Promise.all(promises);
console.log(promises.length); // 5
Where asyncFunction
is something like:
const asyncFunction = (...args) => {
let result = new Promise((resolve, reject) => {
pool.query(...args, (err, rows, fields) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
promises.push(result);
return result;
};
What's happened here is that the first two calls to asyncFunction
push promises into my promises
array, so promises.length
is 2. However, after waiting for them to complete, the 2nd one pushes a bunch of new promises into the array after Promise.all
has already evaluated that array, so they're not awaited.
So, how can I wait for all the promises, plus any new ones? Simply calling await Promise.all(promises)
twice would work in this example, but this could go on ad infinitum.