JS Fetch and retry

PHOTO EMBED

Thu Dec 17 2020 00:22:56 GMT+0000 (Coordinated Universal Time)

Saved by @DBZFYAM #javascript

const fetch_retry = async (url, options, n) => {
    let error;
    for (let i = 0; i < n; i++) {
        
        try {
            response = await fetch(url, options);
            if (response === 200) {
               return response;
            }else{
               throw new Error(response)
            }
        } catch (err) {
           error = err;     
           //1.           
           if (i + 1 === n) throw err;
        }
    }
    throw error;
};
let response = fetch_retry("/someUrl/json", options, 10);
content_copyCOPY

https://medium.com/javascript-in-plain-english/modern-practical-javascript-code-snippets-4002a7a4ba9c