Promise Retry Design Patterns: A Memory-Efficient Approach
When using Promises, retrying operations in the face of failures or until certain conditions are met is a common need. In this article, we will explore three Promise retry design patterns:
1. Retry Until Promise Resolves
This pattern keeps retrying until the Promise resolves. It specifies a maximum retry count and a delay between attempts.
Promise.retry = function(fn, times, delay) {
return new Promise(function(resolve, reject) {
var error;
var attempt = function() {
if (times == 0) {
reject(error);
} else {
fn().then(resolve)
.catch(function(e){
times--;
error = e;
setTimeout(function(){attempt()}, delay);
});
}
};
attempt();
});
};
2. Retry Until Condition on Result is Met
This pattern retries until a specified condition is met on the Promise's result. It also includes a maximum retry count and a delay between attempts.
work.publish()
.then(function(result){
return new Promise(function(resolve, reject){
var intervalId = setInterval(function(){
work.requestStatus(result).then(function(result2){
switch(result2.status) {
case "progress": break; //do nothing
case "success": clearInterval(intervalId); resolve(result2); break;
case "failure": clearInterval(intervalId); reject(result2); break;
}
}).catch(function(error){clearInterval(intervalId); reject(error)});
}, 1000);
});
})
.then(function(){console.log('done')})
.catch(console.error);
3. Memory-Efficient Dynamic Retry
This pattern uses a recursive approach, offering unlimited retries with a configurable delay.
var max = 5;
var p = Promise.reject();
for(var i=0; iBy building a .catch() chain, this pattern allows for concise retry implementations, especially in scenarios with low maximum retry counts or synchronous tests.
Each of these patterns provides a flexible and efficient solution for retrying Promise operations. Depending on your application's requirements, you can choose the pattern that best suits your needs.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3