【问题标题】:Asynchronous function in settimeout called before timesettimeout 中的异步函数在时间之前调用
【发布时间】:2017-09-28 03:07:24
【问题描述】:

我在这里有这个按间隔运行的函数,它的作用是,当它运行时,它设置了 2 个 settimeout。

问题来了,应该在第二次超时之后调用的异步函数在第二次超时甚至触发之前被调用。这是我的代码。

    var runner = Interval.run(function() {
    //-212965881
    bot.sendMessage('-212965881', "Drop usernames now").then(function(){
        ready = 1;
        list = {};
        console.log(ready);
        setTimeout(function(){
            return bot.sendMessage('-212965881',"Round has begun. Please start liking now. Leech check will begin in 1 minute");
        }, 10000);
    }).then(function(){
        ready = 0;
        setTimeout(function(){
            return bot.sendMessage('-212965881',"Leech check has begun!");
        }, 15000);
    }).then(function(){
        //This one fires before 15 seconds
        let msg = {chat:{}};
        msg.chat.id = '-212965881';
        return bot.event('/check', msg);
    }).catch(function(err){
        console.log(err);
    });
},  20000);

不知道为什么会这样。也许我走错了路。 任何人都可以对此有所了解吗?谢谢

【问题讨论】:

标签: javascript node.js asynchronous settimeout


【解决方案1】:

发生这种情况是因为 then 处理程序中的代码正在创建未返回的异步代码,或者基本上是在没有通知 Promise 链活动的情况下“突破”了 Promise 链。

您需要将 setTimeout 包装在 Promise 构造函数中,然后通过在新的 Promises 中解析它们来确保等待内部 bot.sendMessage 调用完成

将其更改为使用 Promise 构造函数,请参阅 Resolving a Promise

var runner = Interval.run(function() {
    //-212965881
    bot.sendMessage('-212965881', "Drop usernames now").then(function(){
        ready = 1;
        list = {};
        console.log(ready);
        return new Promise((resolve) {
            setTimeout(function(){
                resolve(bot.sendMessage('-212965881',"Round has begun. Please start liking now. Leech check will begin in 1 minute"))
            }, 10000);
        });
    }).then(function(){
        ready = 0;
        return new Promise((resolve) {
            setTimeout(function(){
                resolve(bot.sendMessage('-212965881',"Leech check has begun!"))
            }, 15000);
        });
    }).then(function(){
        //This one fires before 15 seconds
        let msg = {chat:{}};
        msg.chat.id = '-212965881';
        return bot.event('/check', msg);
    }).catch(function(err){
        console.log(err);
    });
},  20000);

【讨论】:

    【解决方案2】:

    因为您尝试调用的异步函数会在几秒钟后返回。你写的三个.then 重复工作在第一个Promise 上。

    您可以使用co模块或ES6 async/await来控制多个Promise

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2013-09-25
      相关资源
      最近更新 更多