Reputation:
Can I write my own code to simulate async.waterfall
without using it? I am trying to do using then
but unable to achieve that.
Upvotes: 1
Views: 1039
Reputation: 23029
If you use newer Node.js version with async/await, you can do something like this:
async function waterfall(fns){
let previous = 0;
for (let i=0; i < fns.length; i++) {
console.log(previous, 'start');
previous = await fns[i](previous);
console.log(previous, 'end');
}
console.log('The last result is', previous);
}
const fnsForWaterfall = [input => Promise.resolve(input + 3), input => Promise.resolve(input + 1)]
waterfall(fnsForWaterfall);
Upvotes: 0
Reputation: 434
You can use reduce
to do a waterfall:
function waterfall(funcs) {
return funcs.reduce((acc, func) => acc.then(func), Promise.resolve());
}
Upvotes: 2