Implementing Custom API timeout using the `Promise.race()` method.

You, PromiseJavascriptPromise.race
Back

This tutorial is about creating a custom API timeout for your API calls using Promise.race() method.

hashnode blog link

What is Promise.race() method.

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

Implementation

So, we can provide two inputs inside the race method, i.e:

  1. API call promise.
  2. Delay promise with our custom timeout logic.

    Promise.race([apiCall, timeoutFunc])

Here, The apiCall method will represent our API call promise.

    // your url 
    const apiCall = fetch("https://api.github.com/");

and the timeout function will contain the delay logic which will be responsible for throwing a timeout error.


    function delay(timeOutPeriod) {
    return new Promise((_resolve, reject) => {
        setTimeout(() => reject("Request timeout"), timeOutPeriod);
    });
    }

    const timePeriod =  5000;
    const timeoutFunc = delay(timePeriod);

So, when we will run the Promise.race method, whichever promise is completed first, will return the output.


    Promise.race([apiCall, timeoutFunc])
    .then((data) => data.json())
    .then((data) => console.log("Data : ", data))
    .catch((error) => console.log("Error : "error));

Here, in this particular example, we have provided the custom timeout logic of 5000 milliseconds. So, either the API will give a response with 5 seconds or our network request will get timed out after the 5 seconds.

To check out the code, visit my github link github.

© Jagdish Parihar.RSS