Categories
JavaScript Answers

How to dynamically chain JavaScript promises?

Spread the love

Sometimes, we want to dynamically chain JavaScript promises.

In this article, we’ll look at how to dynamically chain JavaScript promises.

How to dynamically chain JavaScript promises?

To dynamically chain JavaScript promises, we can use the for-of loop and async and await.

For instance, we write:

const myAsyncFuncs = [
  (val) => {
    return Promise.resolve(val + 1);
  },
  (val) => {
    return Promise.resolve(val + 2);
  },
  (val) => {
    return Promise.resolve(val + 3);
  },
];

(async () => {
  for (const f of myAsyncFuncs) {
    const v = await f(1)
    console.log(v)
  }
})()

We have the myAsyncFuncs array that has functions that returns promises.

Then we can run each function sequentially by creating an async function that loops through the functions with a for-of loop.

We get the resolved value of each promise with await.

Therefore, we see 2, 3, and 4 logged for v.

Conclusion

To dynamically chain JavaScript promises, we can use the for-of loop and async and await.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *