Reducing Nested Promises
Solution 1:
The Problem
The problem with your implementation is that all of the promises are created at the same time, and that will cause them to place their asynchronous actions in the event queue at that time. In your case, this is happening in the map
function. Let's walk through this.
// your current codeconst promises = items.map((item, index) => {
console.log(index); // this happens immediately and waits for nothing, which is why you see `0 1 2` in the consolereturndoAsyncThing(item) // right here the async action is created
.then(() => { // this will run as soon as the async action is finishedconsole.log(index);
});
});
After this step, promises
is already an array of promises, all of which have already queued up their asynchronous actions, not waiting for any others to be completed.
Solution
You have the right idea with the reduce, but by the time your reduce runs, all of the promises are already created, and will run in whatever order they finish. If you want to enforce order, you will need to use the reduce to create the promises initially:
const promises = items.reduce((acc, item, index) => {
console.log(index) // still runs immediatelyreturn acc
.then(() =>doAsyncThing(item)) // creates the promise after acc finishes
.then(() =>console.log(index)); // runs after doAsyncThing finishes
}, Promise.resolve());
This will produce the output 0 1 2 0 1 2
in your console, but action 1 will still not be run until action 0 finishes, and action 2 will not be run until action 1 finishes. I hope this helps!
Post a Comment for "Reducing Nested Promises"