node流程控制,定次循环执行异步请求或方法

在写程序中,经常会遇到循环请求某个接口或者执行某个方法,然后某个条件去终止它,或者到达最大次数自动终止,我把asyn.retry方法封装了下,调用起来更方便一点,调用代码如下:

const MyProcess = require('MyProcess'); //引入自定义流程控制模块

const config = {
    times:5, //最大调用次数5次
    interval:1000, //间隔1000ms执行一次
    processFunction:function () { //自定义函数,当reject时会继续调用直到最大次数,resolve则会返回结果
       return new Promise((resolve,reject)=>{
           console.log(this.data);
           //resolve('success);
           reject('timerout');
       });
    },
    data:{name:'jack',age:13,msg:'test'} //自定义函数中需要的数据
}

const mp  = new MyProcess(config);
mp.retry().then((data)=>{
    //成功处理
    console.log(data)
}).catch((err)=>{
    //失败处理
    console.log(err)
});

调用起来是不是很简单呢!  MyProcess模块代码如下:

var async = require('async');
/**
 * @author liu_qi
 * @date 2018-8-2
 * @version 0.01
 *
 * 构造器说明:
 *  times:执行的次数
 *  interval:执行的间隔/毫秒
 *  processFunction:要求必须返回一个Promise对象,resolve则停止执行,reject:继续执行,直到最大次数
 *  data:需要在processFunction中使用的数据,可以使用this.data调用
 * */
class MyProcess{
    constructor(config){
        if(!config){
            throw 'config is missing! ';
        }
        if(typeof config.times != 'number'){
            throw 'config.times must be number !';
        }
        if(typeof config.interval != 'number'){
            throw 'config.interval must be number !';
        }
        if(typeof config.processFunction != 'function'){
            throw 'config.processFunction must be function !';
        }
        this.times = config.times;
        this.interval = config.interval;
        this.processFunction = config.processFunction;
        this.data = config.data;
    }

    nextTick(callback){
        this.processFunction().then((data)=>{
            callback( null,data);
        }).catch((err)=>{
            callback(err);
        });
    }

    retry(){
        return new Promise((resolve,reject)=>{
            async.retry({
                times : this.times,
                interval : this.interval
            }, this.nextTick.bind(this),(err, data)=> {
                if(err){
                    return reject(err);
                }
                resolve(data)
            });
        });
    }

}

module.exports = MyProcess;

感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!

发布了29 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Baby_lucy/article/details/86693501