node开发,使用node-schedule做定时任务,定时任务内的数组被循环了两遍,求解

我使用node-schedule模块过程中遇到个问题,在定时任务中循环一个数组order,数组长度只有2,每循环一次就会在数据表中创建一条数据,按道理讲应该只创建两条数据,但是这个数组在定时任务里面循环了两遍创建了四条数据。如果把for循环放到定时任务scheduleJob外面,这个数组只会被循环一遍,求解。


代码如下:

schedule.scheduleJob('30 50 15 * * *',function(){
    console.log('定时任务');
    for(let i=0;i<order.length;i++){
        console.log("for循环");
        console.log('i:',i);
        const finalPrice = order[i].finalPrice;
        const earning = countEarning(finalPrice,selfRate);
        const divided = countEarning(finalPrice,uplineRate);
        console.log("earning:",earning);
        console.log("divided:",divided);
        const orderearnMsg = {
            uid: order[i].uid,
            oid: order[i].orderId,
            price: order[i].finalPrice,
            earning: earning,
            divided: divided,
            year: year,
            month: month,
            day: day,
            time: time
        }
        Orderearn.create(orderearnMsg).then(function(orderearnRes){
            console.log('create success');
        })
    }
})
阅读 2.8k
2 个回答

是我对这个定时模块理解不够,我为了调用我写的定时任务,使用了setinterval进行测试,每15秒调用一次,我以为无论调用频率多高定时任务也都只会在某一秒执行,没想到一秒内也会执行好多次(手动捂脸),所以导致for循环执行多次,怪小弟学艺不精……

应该不是定时器的问题,而是你for循环的问题,你for循环内是一个异步操作,可能会出现问题,得不到你想要的结果。改写为:

for(){
    var o=order[i];
    (function(o){
        //
    })(o);
    
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题