Home >Web Front-end >JS Tutorial >How to Implement Promise Retry Design Patterns for Efficient Error Handling?
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.
<code class="javascript">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(); }); };</code>
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.
<code class="javascript">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);</code>
3. Memory-Efficient Dynamic Retry
This pattern uses a recursive approach, offering unlimited retries with a configurable delay.
<code class="javascript">var max = 5; var p = Promise.reject(); for(var i=0; i<max; i++) { p = p.catch(attempt).then(test).catch(rejectDelay); } p = p.then(processResult).catch(errorHandler);</code>
By 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.
The above is the detailed content of How to Implement Promise Retry Design Patterns for Efficient Error Handling?. For more information, please follow other related articles on the PHP Chinese website!