I want to add retry logic to my javascript HTTP service, which internally uses Axios and returns promises. Goal is to retry fetch/post until it resolves or retry limit is exceeded. I came up with this draft (not working as it is)
fetchSomething(numRetry) {
if (!numRetry)
numRetry = 0
return new Promise(function(resolve, reject) {
axios.get('/services/rest/vopa/sanomaloki/virheet')
.then(response => resolve(response))
.catch(response => {
if (numRetry > FETCH_RETRY_LIMIT)
reject(response)
else
return fetchSomething(numRetry + 1)
})
});
}
As far as I know, calling fetchSomething in catch creates new resolve and reject functions, but I would like it to resolve or reject the original promise
How about this simpler version (untested!):
function fetchSomething(numRetry = 0) {
return axios.get('/services/rest/vopa/sanomaloki/virheet')
.catch(response => {
if (numRetry > FETCH_RETRY_LIMIT)
return Promise.reject(response); // pass it on
else
return fetchSomething(numRetry + 1); // might work
});
}
You don't need to create a new Promise
. Actually using Promise constructor indicates you are doing something wrong. Demo.
function fetchSmth(num) {
num = num || 0
return num > FETCH_RETRY_LIMIT
? Promise.reject(new Error('Fetch retry limit reached'))
: axios
.get('/services/rest/vopa/sanomaloki/virheet')
.catch(fetchSmth.bind(null, num + 1))
}