You create several promises, but they are all asynchronous. You build Promise1, Promise2, Promise3, ... but as soon as they are in the wild, they all shoot at the same time. If you want synchronous behavior, you need to bind them together, so that Promise1.then () does Promise2 and so on. I used to use Array.reduce for this.
someAPIpromise().then((items) => { items.reduce((accumulator, current) => accumulator.then(() => Promise.all[myPromiseA(item), myPromiseB(item)]).then(() => doSomethingSynchronouslyThatTakesAWhile(); ) ) , Promise.resolve());
You can write this as a helper function if you want, which can make everything clearer.
function execSequentially (arr, func) { return arr.reduce( (accumulator, current) => accumulator.then(() => func(current)), Promise.resolve()); }
This function is performed as
execSequentially(items, item => console.log(item));
of course, replacing console.log with what you want to do.
The auxiliary function approach is also less invasive of change. The helper applies to your source code:
someAPIpromise().then((items) => { execSequentially(items, (item) => Promise.all[myPromiseA(item), myPromiseB(item)]).then(() => { doSomethingSynchronouslyThatTakesAWhile(); }); ); });
source share