Since you seem to be using the Bluebird promise library, you have a number of built-in options to organize the returned promise functions. You can use Promise.reduce() , Promise.map() with a concurrency value of 1, Promise.mapSeries or Promise.each() . If the iterator function returns a promise, they will all wait for the next iteration until that promise is resolved. What to use more depends on the mechanics of how your data is structured and what kind of result you want (neither what you actually show nor describe).
Suppose you have a set of functions that return a promise, and you want to name them one at a time, waiting for it to be resolved before calling the next one. If you want to get all the results, I would suggest Promise.mapSeries() :
let arrayOfPromiseReturningFunctions = [...]; // call all the promise returning functions in the array, one at a time // wait for one to resolve before calling the next Promise.mapSeries(arrayOfPromiseReturningFunctions, function(fn) { return fn(); }).then(function(results) { // results is an array of resolved results from all the promises }).catch(function(err) { // process error here });
Promise.reduce() can also be used, but it will accumulate one result, passing it from one to another and ending with one final result (for example, Array.prototype.reduce() ).
Promise.map() is a more general version of Promise.mapSeries() that allows you to control the number of concurrency (the number of asynchronous operations in flight at the same time).
Promise.each() will also streamline your functions, but does not accumulate the result. It assumes that you either have no result, or you accumulate the result out of range or through side effects. I do not like to use Promise.each() because I do not like programming side effects.
source share