- Published on
Retrying Promises like API Request in JavaScript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
If we're performing something async like for example making an API call, then the chance of it getting failed to various factors like network failure can happen often.
So it's recommended to have a retry logic especially if it's something critical.
For such cases, p-retry by Sindre Sorhus might be a good choice for us.
With this package, we can easily add retry logic for any promise-returning or async function
Dependency
npm install p-retry
npm install node-fetch # used in the example snippet
Snippet
// Based on p-retry's README example
import pRetry, {AbortError} from 'p-retry';
import fetch from 'node-fetch';
const run = async () => {
const response = await fetch('https://randomuser.me/api/');
// Abort retrying if the resource doesn't exist
if (response.status === 404) {
throw new AbortError(response.statusText);
}
return response.json();
};
console.log(await pRetry(run, {retries: 5}));
In this case, our logic will try the API call again and again until the threshold is reached.
Check out their docs for more snippets and details about its configuration.
Happy retrying Promises!