Promise Retry Designs
Promises allow for asynchronous programming, providing a flexible and efficient mechanism for handling asynchronous operations. However, it may be necessary to design patterns to handle scenarios where a promise requires retries. Here we present three different promise retry design patterns:
<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>
<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); }); })</code>
We explore an alternative approach based on building a .catch() chain instead of the usual .then() chain:
<code class="javascript">var max = 5; var p = Promise.reject(); for(var i=0; i<max; i++) { p = p.catch(attempt).catch(rejectDelay); } p = p.then(processResult).catch(errorHandler);</code>
This pattern is suitable for scenarios with a limited number of retries and a low maximum number to avoid memory consumption issues.
<code class="javascript">var max = 5; var p = Promise.reject(); for(var i=0; i<max; i++) { p = p.catch(attempt).then(test); } p = p.then(processResult).catch(errorHandler);</code>
<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); // Don't simplify this to `p.catch(attempt).then(test, rejectDelay)` as test failures won't be caught. } p = p.then(processResult).catch(errorHandler);</code>
The above is the detailed content of What Are the Essential Promise Retry Design Patterns for Handling Asynchronous Operations?. For more information, please follow other related articles on the PHP Chinese website!