Last active
November 16, 2021 10:40
-
-
Save abdullahoguk/1ee355a3501a4d18911c64decf73eb81 to your computer and use it in GitHub Desktop.
Fetch Js - Async and retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = require("node-fetch"); | |
async function fetchAsync (url, type) { | |
const init = { | |
headers: { | |
"content-type": "text/html;charset=UTF-8", | |
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" | |
} | |
} | |
const response = await fetch(url,init); | |
if (type=="json"){ | |
return await response.json(); | |
} | |
else{ | |
return await response.text(); | |
} | |
} | |
const fetchRetry = async (url, options, attempt) => { | |
try { | |
const response = await fetch(url, options); | |
if(!response.ok) { | |
throw new Error("Invalid response."); | |
} | |
return response; | |
} catch (error) { | |
if (attempt <= 1) { | |
throw error; | |
} | |
await self.sleep(2000); | |
return fetchRetry(url, options, attempt - 1); | |
} | |
}; | |
module.exports = {fetchAsync, fetchRetry} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment