编辑
代码为#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) 我必须制作一系列fetch()Promise:我一次只有1个url,这意味着只有1个fetch()promise.每次我收到一个json,这个包含另一个json的url,所以我必须做出另一个fetch()承诺.
我可以使用多个承诺,但在这种情况下我不能这样做Promise.all(),因为我没有所有网址,只有一个网址.
这个例子不起作用,它都冻结了.
function fetchNextJson(json_url)
{
return fetch(json_url, {
method: 'get'
})
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json);
return json;
})
.catch(function(err) {
console.log('error: ' + error);
});
}
function getItems(next_json_url)
{
if (!(next_json_url)) return;
get_items = fetchNextJson(next_json_url);
interval = $q.when(get_items).then(function(response) {
console.log(response);
next_json_url = response.Pagination.NextPage.Href;
});
getItems(next_json_url);
}
var next_json_url = 'http://localhost:3000/one';
getItems(next_json_url);
Run Code Online (Sandbox Code Playgroud)