For more tips like this, sign up to the weekly newsletter!

Wait in an async function

When you have an async function, you might need to delay part of the execution. Do something, wait a bit, then do something else.

How to do this?

With Promises, it is a matter of adding a Promise that resolve after some time:

.then(() => {
  // wait a little...
})

But how to wait?

You can combine the Promise constructor with a setTimeout:

new Promise((res) => setTimeout(res, 1000));

This Promise waits 1 second and then resolves. So a waiting step looks like this:

.then(() => {
  return new Promise((res) => setTimeout(res, 1000));
})

Then if you use async/await you can simply await this Promise:

// do something
await new Promise((res) => setTimeout(res, 1000));
// do something else

This will have the effect of pausing the execution for 1 second.

Try it
Learn more: