Skip to main content

Command Palette

Search for a command to run...

Promise waterfall

Published
1 min readView as Markdown

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(() => {
      resolve(true);
    }, 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([]))

Conclusion

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