Node.js async.each抛出" Callback已被调用"

时间:2016-07-19 17:42:29

标签: javascript node.js asynchronous callback

这个问题似乎与许多其他问题重复,但我无法在任何地方找到错误。

问题是async.each抛出" Callback已被调用"。这是代码段(我将其命名为异步回调done,因此它不会与我的代码中的其他回调混淆):

async.each(this.requirements, (requirement, done) => {
  // That thing here passes the result as a callback
  requirement.callback((result) => {
    if (!result) {
      // requirement not passed -> return error
      done(true); // LINE 42
    } else {
      done(); // LINE 44
    }
  }, data, params, bot);
}, (err) => {  // 'done' callback
  log.info('handler',
    `Handler '${this.label}' ${err ? 'failed' : 'succeeded'}`);
  // if any requirement did not pass, do not execute handler callback
  if (!err) this.callback(data, params, bot);
});

这里是它的堆栈跟踪:

C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:837
          if (fn === null) throw new Error("Callback was already called.");
                           ^

Error: Callback was already called.
    at C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:837:34
    at requirement.callback (C:\Users\samuel\Code\node\sk22tgjs\node_modules\telegramjs\core\handler.js:44:11)
    at Requirement.exports.command.Requirement.callback (C:\Users\samuel\Code\node\sk22tgjs\node_modules\telegramjs\telegram\requires.js:21:5)
    at async.each (C:\Users\samuel\Code\node\sk22tgjs\node_modules\telegramjs\core\handler.js:39:19)
    at C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:2953:18
    at replenish (C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:872:19)
    at C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:878:27
    at C:\Users\samuel\Code\node\sk22tgjs\node_modules\async\dist\async.js:840:18
    at requirement.callback (C:\Users\samuel\Code\node\sk22tgjs\node_modules\telegramjs\core\handler.js:44:11)
    at Requirement.callback (C:\Users\samuel\Code\node\sk22tgjs\node_modules\telegramjs\core\requires.js:19:5)

有趣的是,只有在done(true)被调用时才会出现问题。然而,错误发生在第44行,而不是42.

您还可以在GitHub上看到损坏的代码,尤其是testing分支:https://github.com/22sk/telegramjs

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果找不到命令,则会调用成功和失败,而不仅仅是失败。

https://github.com/22sk/telegramjs/blob/5b85f04fe890a8fd32b373edb97bfebc923156b1/bot/telegram/requires.js

exports.command = new Requirement({
  label: 'command',
  requires: requires.has('message', 'text'),
  callback: (result, data, params, bot) => {
    const command = new Command(data.message.text);
    if (!command.valid || command.bot && bot.me.username !== command.bot) {
      // command is not valid or not meant to be handled by this bot
      result(false); // <--- ### Missing return ### --->
    }
    // command is valid and should be handled by this bot
    // write command into data
    params.command = command;
    result(true);
  }
});