编辑
- 不断重试直到承诺解决的模式(使用
delay
和maxRetries
)。 - 不断重试直到条件满足结果的模式(使用
delay
和maxRetries
)。 - 具有无限重试的内存高效动态模式(
delay
提供)。
#1 的代码。 继续重试直到 promise 解决(语言的任何改进社区等?)
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();
});
};
利用
work.getStatus()
.then(function(result){ //retry, some glitch in the system
return Promise.retry(work.unpublish.bind(work, result), 10, 2000);
})
.then(function(){console.log('done')})
.catch(console.error);
#2 的代码 继续重试,直到 then
上的条件满足导致可重用的方式(条件会有所不同)。
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);
原文由 user2727195 发布,翻译遵循 CC BY-SA 4.0 许可协议
有点不同……
异步重试可以通过构建
.catch()
链来实现,而不是更常见的.then()
链。这种方法是:
否则,使用递归解决方案。
首先,一个实用函数用作
.catch()
回调。现在您可以非常简洁地构建 .catch 链:
1.重试直到承诺解决,延迟
演示: https ://jsfiddle.net/duL0qjqe/
2. 重试直到结果满足某个条件,不要延迟
演示: https ://jsfiddle.net/duL0qjqe/1/
3.重试直到结果满足某些条件,延迟
考虑完 (1) 和 (2) 后,组合测试+延迟同样微不足道。
test()
可以是同步的也可以是异步的。添加进一步的测试也是微不足道的。只需将一串 thens 夹在两个锁扣之间即可。
演示: https ://jsfiddle.net/duL0qjqe/3/
所有版本都设计为
attempt
是一个返回承诺的异步函数。它也可以想象地返回一个值,在这种情况下,链将沿着它的成功路径到达下一个/终端.then()
。