admin管理员组文章数量:1136149
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.
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.
- 2 Totally just googled your question word for word – lonewarrior556 Commented Feb 12, 2016 at 19:58
7 Answers
Reset to default 105Same 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]);
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 Promise
s), which return Promise
.
Building on @torazaburo, we can also add an 'unhappy path'
funcs.reduce(function(prev, cur) {
return prev.then(cur).catch(cur().reject);
}, starting_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));
}
For possible empty funcs
array:
var promise = $.promise(function(done) { done(); });
funcs.forEach(function(func) {
promise = promise.then(func);
});
If you're using ES7 and need something thenable
and similar to Promise.all()
, this seems to work.
Promise.resolve(
(async () => {
let results = []
for (let promise of promises) {
results.push(await promise)
}
return results
})()
)
本文标签:
版权声明:本文标题:javascript - How to chain execution of array of functions when every function returns deferred.promise? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736955324a1957572.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论