user9586039
user9586039

Reputation:

Is there any alternative to async.waterfall?

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

Answers (2)

libik
libik

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

Jspdown
Jspdown

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

Related Questions