Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain execution of array of functions when every function returns deferred.promise?

Same idea, but you may find it slightly classier or more compact:

funcs.reduce((prev, cur) => prev.then(cur), starting_promise);

If you have no specific starting_promise you want to use, just use Promise.resolve().


You need to build a promise chain in a loop:

var promise = funcs[0](input);
for (var i = 1; i < funcs.length; i++)
    promise = promise.then(funcs[i]);

Building on @torazaburo, we can also add an 'unhappy path'

funcs.reduce(function(prev, cur) {
  return prev.then(cur).catch(cur().reject);
}, starting_promise); 

ES7 way in 2017. http://plnkr.co/edit/UP0rhD?p=preview

  async function runPromisesInSequence(promises) {
    for (let promise of promises) {
      console.log(await promise());
    }
  }

This will execute the given functions sequentially(one by one), not in parallel. The parameter promises is a collection of functions(NOT Promises), which return Promise.


ES6, allowing for additional arguments:

function chain(callbacks, initial, ...extraArgs) {
 return callbacks.reduce((prev, next) => {
   return prev.then((value) => next(value, ...extraArgs));
 }, Promise.resolve(initial));
}