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 Promise
s), 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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With