编辑
代码为#1.继续重试,直到诺言解决(语言的任何改进社区等?)
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();
});
};
Run Code Online (Sandbox Code Playgroud)
使用
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);
Run Code Online (Sandbox Code Playgroud)
#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) { …Run Code Online (Sandbox Code Playgroud)