I am calling a function which essentially returns a promise that resolves with either a list or nothing. I then call the same function for each item in the list. Eventually, all will resolve with nothing. I would like to run some code only when all resolve, but cannot figure out how to do that.
To simplify my problem I created this example. I have control only over the recursive function. Saving all the promises to an array and passing it to Promises.all() in sample below:
function randomLowerInt(int) {
return parseInt(Math.random() * int);
}
function smallerArray(size) {
const arr = [];
const smallerSize = randomLowerInt(size);
for (let i = 0; i < smallerSize; i++) {
arr.push(i);
}
return arr;
}
function createPromise(arrLength) {
const secnds = parseInt(Math.random() * 20) * 1000;
const timeCreated = new Date().getTime();
const p = new Promise(res => {
setTimeout(() => {
const timeResolved = new Date().getTime();
res({
timeCreated,
timeResolved,
arrLength
});
}, secnds);
});
return p;
}
function recursive(arr) {
arr.forEach(() => {
createPromise(arr.length).then(({
timeCreated,
timeResolved,
arrLength
}) => {
// console.log({
// timeCreated,
// timeResolved
// });
const smallerArr = smallerArray(arrLength);
recursive(smallerArr);
});
});
}
recursive([1, 2, 3, 4, 5]);
const promises = [];
function recursive2(arr) {
arr.forEach(() => {
const p = createPromise(arr.length).then(({
timeCreated,
timeResolved,
arrLength
}) => {
const smallerArr = smallerArray(arrLength);
recursive2(smallerArr);
return ({
timeCreated,
timeResolved
});
});
promises.push(p);
});
}
recursive2([1, 2, 3, 4, 5]);
console.log('Waiting...');
Promise.all(promises).then(vals => console.log(vals));
doesn't work because Promise.all()
will get called before the array is fully populated.