const axios = require('axios');
async function fetchDataWithRetry(url, retries = 3) {
try {
const response = await axios.get(url);
console.log('Data fetched:', response.data);
} catch (err) {
if (retries > 0) {
console.log(`Retrying... Attempts left: ${retries}`);
await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
return fetchDataWithRetry(url, retries - 1); // Retry the API call
} else {
console.error('Failed after retries:', err.message);
}
}
}
fetchDataWithRetry('https://jsonplaceholder.typicode.com/posts');
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter