【问题标题】:A function does not exit when return passes a function containing promise当 return 传递包含 promise 的函数时,函数不会退出
【发布时间】:2018-09-04 05:31:16
【问题描述】:

好吧,我遇到了一个棘手的问题……
此代码针对不和谐机器人收到的每条消息运行...
首先是functionA,它检查消息是否与字符串匹配。
如果字符串匹配,则functionA 将返回functionB
有趣的是,当functionA 返回包含承诺的functionBfunctionB 包含承诺)时,事情就变得不确定了……

当我们返回时,这段代码退出了函数……

const discord = require("discord.js");
const client = new discord.Client();

client.on('message', msg => { // msg is "test"
  let app = (function functionA() {
    if(msg.content == "test") { // should be true
      return function functionB() {
        console.log("response") // regular console log
      }
    }
    console.log("should not run") // this does not run, which is good
  })()

  if(typeof app == "function") {
    app();
  }
});

client.login(DISCORD_BOT_TOKEN);

然而,这段代码并没有……

const discord = require("discord.js");
const client = new discord.Client();

client.on('message', msg => { // msg is "test"
  let app = (function functionA() {
    if(msg.content == "test") { // should be true
      return function functionB() {
        msg.channel.send("response") // a promise
      }
    }
    console.log("should not run") // this runs for some reason…
  })()

  if(typeof app == "function") {
    app();
  }
});

client.login(DISCORD_BOT_TOKEN);

msg.chanel.send("respons") 方法确实返回了一个承诺(我实际上不确定这是否会影响任何事情),
但是functionB 本身应该在我们返回时退出functionA

为什么函数没有停止?为什么return 不退出函数?

【问题讨论】:

  • 你能在你的 if 条件中放一个日志吗......只是为了验证它是否会去那里?
  • 我试过了……条件为真,if语句的内容运行
  • 抱歉,我们需要minimal reproducible example。您显示的代码与您描述的不同。
  • 尝试console.log("should not run", msg.content, msg.content === 'test') 以获得更好的概览。或者尝试在调试器中设置断点以逐步执行每一行。
  • 感谢 Discord 上的某个用户……我意识到我很愚蠢……机器人发送了另一条不是 test 的消息,因此该函数必须运行 should not run 日志

标签: javascript node.js promise discord.js


【解决方案1】:

原来我是个白痴…… 机器人发送另一条消息…response 然后触发一个与 if case 测试不匹配的消息事件…从而发送 should not run 让我无法入睡的日志 ¬_¬

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多