Categories
JavaScript Answers

How to Use setTimeout in JavaScript Promise Chain?

Spread the love

Sometimes, we want to use the setTimeout function in a JavaScript promise chain.

In this article, we’ll look at how to use the setTimeout function in a JavaScript promise chain.

Create a Function that Returns a Promise that uses setTimeout

We can create a function that returns a promise that calls setTimeout so that we can use setTimeout in a promise chain.

For instance, we can write:

const delay = (t, v) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(v), t)
  });
}

(async () => {
  const one = await Promise.resolve(1)
  console.log(one)
  const two = await delay(1000, 2)
  console.log(two)
  const three = await Promise.resolve(3)
  console.log(three)
})()

to create the delay function that returns a promise by creating one with the Promise constructor.

We pass in a callback that calls setTimeout , which calls resolve with v and delays the execution of the callback by t milliseconds.

Then we use delay in an async function with other promises.

Now we should see a delay when we’re calling delay .

And 1, 2, and 3 are logged in the console log.

Conclusion

We can create a function that returns a promise that calls setTimeout so that we can use setTimeout in a promise chain.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.