2017-09-28 2 views
-1

この関数は間隔で実行され、実行されると、2つのsettimeoutが設定されます。時刻の前にsettimeoutの非同期関数が呼び出されました

2番目のタイムアウトがトリガーされる前に2番目のタイムアウト後に呼び出される非同期関数が問題です。これは私のコードです。

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

これがどうして起こるかわかりません。おそらくそれについて間違った方法で行っています。 誰もこれにいくつかの光を投げることができますか?ありがとう

+0

[非同期呼び出しから応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous- call) –

+2

'setTimeout()'は後で非同期で実行するようにスケジュールしますが、実行を一時停止しません。また、 'setTimeout()'に渡した関数からの戻り値も無視されます。 – nnnnnn

答えて

0

thenハンドラ内のコードが、返された非同期コードを作成しているか、Promiseチェーンのアクティビティを通知せずにPromiseチェーンから基本的に「抜け出す」ためです。あなたが約束コンストラクタの内部であなたのsetTimeoutをラップし、その後もResolving a Promise

を参照してください、あなたはそれが約束コンストラクタを使用するように新しい Promises

変更の内側に、それらを解決することによって終了する内装用bot.sendMessage呼び出しを待つことを確認する必要があり

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

あなたが呼び出しようとしていた非同期関数が数秒後に返されるためです。あなたが書いた3つの.thenは、最初にPromiseで動作します。

coモジュールを使用するか、ES6 async/awaitを使用してPromiseを複数制御することができます。

関連する問題