Categories
JavaScript Answers

How to time out a Node Promise if failed to complete in time?

Spread the love

To time out a Node Promise if failed to complete in time, we use the Promise race method.

For instance, we write

const race = Promise.race([
  new Promise((resolve) => {
    setTimeout(() => {
      resolve("I did it");
    }, 1000);
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("Timed out");
    }, 800);
  }),
]);

try {
  const data = await race;
} catch (e) {
  console.log(e);
}

to call Promise.race with an array of promises.

We call reject in the 2nd Promise callback to reject the promise after 800ms.

Then we use await to run the promise returned by race.

And then we get the data from the promise.

We catch the rejection with the catch block.

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 *