Promise waterfall

JavaScript promise is very useful, but if you have unpredictable tasks that depend on the previous task or can't run parallel, this syntax can be helpful.

Waterfall syntax

Start by prepare a promise function called run

const run = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
    }, 1000);

Then use reduce get the output of the previous task

Array.from({ length: 10 }).reduce(function(prev, curr) {
  return prev.then(() => {
    return run()
}, Promise.resolve([]))


Absolutely you can use another package like async to solve this problem. But if you want to have a lightweight solution, it can help.

No Comments Yet