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

点点圈 提交于 2019-11-26 13:48:31

问题


I have created my first deferred object in Node.js using deferred module and it works great when I pass result to next function and trigger resolve and reject.How to chain execution of array of functions when every function returns deferred.promise ? I have like input parameters array of functions and input parameter for first function and every next function get parameter from previous.

It works like f1(100).then(f2).then(f3), but how when I have n number of functions.


回答1:


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]);



回答2:


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().




回答3:


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

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



回答4:


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));
}



回答5:


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.




回答6:


For possible empty funcs array:

var promise =  $.promise(function(done) { done(); });
funcs.forEach(function(func) {
  promise = promise.then(func);         
});


来源:https://stackoverflow.com/questions/21372320/how-to-chain-execution-of-array-of-functions-when-every-function-returns-deferre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!