Created
September 17, 2022 07:49
-
-
Save semlinker/8331c7f86f1a09e5847ed8cbe5146028 to your computer and use it in GitHub Desktop.
Axios request retry example (adapter)
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Axios request retry example (adapter)</title> | |
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> | |
</head> | |
<body> | |
<h3>Axios request retry example (adapter)</h3> | |
<button onclick="requestWithoutRetry()">WithoutRetry</button> | |
<button onclick="requestWithRetry()">WithRetry</button> | |
<script> | |
function retryAdapterEnhancer(adapter, options) { | |
const { times = 0, delay = 300 } = options; | |
return async (config) => { | |
const { retryTimes = times, retryDelay = delay } = config; | |
let __retryCount = 0; | |
const request = async () => { | |
try { | |
return await adapter(config); | |
} catch (err) { | |
if (!retryTimes || __retryCount >= retryTimes) { | |
return Promise.reject(err); | |
} | |
__retryCount++; | |
const delay = new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(); | |
}, retryDelay); | |
}); | |
return delay.then(() => { | |
return request(); | |
}); | |
} | |
}; | |
return request(); | |
}; | |
} | |
const http = axios.create({ | |
baseURL: "http://localhost:3000/", | |
adapter: retryAdapterEnhancer(axios.defaults.adapter, { | |
retryDelay: 1000, | |
}), | |
}); | |
function requestWithoutRetry() { | |
http.get("/users"); | |
} | |
function requestWithRetry() { | |
http.get("/users", { retryTimes: 2 }); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Verify Github on Galxe. gid:UwHFVPkBP55Kzdc5Df366D