R
R
rusrich2021-02-09 16:45:17
React
rusrich, 2021-02-09 16:45:17

How to make fetch js make multiple request attempts when getting an error?

Good evening.

Can you please tell me how to use fetch to make a second request request when an error is received.
I would like, of course, to try to reach the server three times, and after that return an error if this did not happen.

Is there some special syntax or just using IF?

Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2021-02-09
@dimoff66

The second parameter then is a function on error, pass a link to the fetch call function into it. Approximately so

const fetchData = () => {
  fetch(url).then(
   response = > { 
     // код при успешном ответе
   }, fetchData)
}

fetchData()

L
Loli E1ON, 2021-02-09
@E1ON

try {
  request();
} catch(e) {
  request();
}

A
Alexander, 2021-02-09
@Seasle

const getMethod = (url, repeatCount = 1) => fetch(url)
    .then(response => {
        if (!response.ok) {
            return repeatCount > 1
                ? get(url, repeatCount - 1)
                : Promise.reject(response);
        }

        return response;
    })
    .then(response => response.json());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question