Created
April 25, 2019 13:00
-
-
Save shettayyy/4e55b53f4dec713b4d3ce10770de7f36 to your computer and use it in GitHub Desktop.
If the API fails then this code will help in retrying the call
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
(function() { | |
sleep = ms => { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
}; | |
async function getTokenFromApi() { | |
let retries = 2; | |
async function poll(apiCallback) { | |
let response = {}; | |
try { | |
response = await apiCallback(); | |
response.status = 202; | |
if(response.status === 202) { | |
if(retries > 0) { | |
retries -= 1; | |
await sleep(1000); | |
return poll(apiCallback); | |
} else { | |
return Promise.reject(new Error("something bad happened")); | |
} | |
} | |
} catch(err) { | |
return err; | |
} | |
return response; | |
} | |
try { | |
console.log(await poll(() => axios.get('https://jsonplaceholder.typicode.com/posts'))); | |
} catch(err) { | |
console.log('Major major err'); | |
} | |
} | |
getTokenFromApi(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment