I have a function which returns a javascript Promise and inside it there runs some asynchronously code. The async code, needs to be retried for couple of times in cases it fails. I was doing that, till I observed some strange behaviors which made me wonder if I'm doing it right. So I had to change it. Both approaches snipped are down here. I have some idea why the first approach (asyncFunc) doesn't work, I would appreciate if someone could share some technical clarity about it. And for the second approach (ayncFunc_newer) any suggestion on how it can be done better?
var _retryCount = 0;
// this is what I was doing
function asyncFunc () {
return new Promise(function(fulfill, reject) {
doAsync()
.then(fulfill)
.catch(retry);
function retry(promiseResult) {
if(_retryCount < 3) {
_retryCount++;
return asyncFunc();
}
else {
reject(promiseResult);
}
}
});
}
// this what I'm doing now
function ayncFunc_newer() {
return new Promise(function(fulfill, reject) {
var retryCount = 0;
doAsync()
.then(fulfill)
.catch(onReject);
function onReject(bmAuthError) {
if(retryCount < 3) {
retryCount++;
logWarning(error);
doAsync()
.then(fulfill)
.catch(onReject);
}
else {
fulfill(false);
}
}
});
};
Best practice is to avoid the promise constructor anti-pattern. Basically,
new Promise
exists mostly to wrap non-promise APIs, so if your functions already return promises, then there's usually a way to avoid using it.If you're doing a low fixed number retries, then your case is as simple as:
For a configurable number of retries, you'd expand this to:
Or for higher number of retries, you could use a recursive approach: