【发布时间】:2018-09-04 05:31:16
【问题描述】:
好吧,我遇到了一个棘手的问题……
此代码针对不和谐机器人收到的每条消息运行...
首先是functionA,它检查消息是否与字符串匹配。
如果字符串匹配,则functionA 将返回functionB。
有趣的是,当functionA 返回包含承诺的functionB(functionB 包含承诺)时,事情就变得不确定了……
当我们返回时,这段代码退出了函数……
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