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

2021-03-48更新:已经有大佬写了库了 传送门->async-retry

 

在写程序中,经常会遇到循环请求某个接口或者执行某个方法,然后某个条件去终止它,或者到达最大次数自动终止,我把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;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值