相关疑难解决方法(0)

承诺重试设计模式

编辑

  1. 继续重试的模式,直到promise结算(使用delay和maxRetries).
  2. 继续重试的模式,直到条件满足结果(使用delay和maxRetries).
  3. 具有无限重试的内存高效动态模式(提供延迟).

代码为#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)

javascript node.js promise

53
推荐指数
9
解决办法
4万
查看次数

多个,顺序fetch()承诺

我必须制作一系列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)

javascript json promise angularjs es6-promise

3
推荐指数
1
解决办法
3063
查看次数

标签 统计

javascript ×2

promise ×2

angularjs ×1

es6-promise ×1

json ×1

node.js ×1