承诺重试设计模式

  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();

    });

};

使用


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);


慕森卡
浏览 564回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP