how to make second request if .catch on promise is executed?

Viewed 48

how can I make a second request if .catch on promise is executed , in order to get the data successfully

because if .catch is executed I did not received the data. and I have to refresh the page again to get the data.

fetch("https://randomuser.me/api")
.then(result => result.json())
.then(data => {
    console.log(data)
})
.catch(error => console.log(error))
2 Answers

You just want to retry in the catch? You will need to call the function that makes the request again. This is called recursion. Ie:

function makeRequest() {
  fetch("https://randomuser.me/api")
    .then((result) => result.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.log(error);
      return makeRequest(); // Calls itself recursively
    });
}

However this introduces the possibility of an infinite loop, so you need some way to break out, maybe like this:

function makeRequest(attempt=0) {
  const maxRetries = 3;
  if (attempt > maxRetries) {
    throw new Error(`Could not fetch user after ${attempt} attempts`);
  }

  fetch("https://randomuser.me/api")
    .then((result) => result.json())
    .then((data) => {
      console.log(data);
    })
    .catch((error) => {
      console.log(error);
      // Call self and increment the attempt number.
      // Very important to ensure that the break condition
      // can be met or we can end up calling the function
      // forever with no way to escape. This is called an
      // infinite loop.
      return makeRequest(attempt + 1);
    });
}

You can also make the logic more complex for retries, like introduce a timeout before the next request if attempt is gt 0, add exponential backoff etc.

Always remember to be careful of infinite loops when using recursive functions.

You can put the fetch and .json() calls into a function, then call that function once (immediately), and call it again inside the .catch if needed:

const getData = () => fetch("https://randomuser.me/api")
  .then(result => result.json())

getData()
  .then(console.log)
  .catch((error) => {
    console.log(error);
    return getData();
  });
  .catch((error2) => {
    // Could not get response after 2 attempts
    console.log(error2);
  });
Related