【问题标题】:Chaining Promises to perform two actions链接 Promise 以执行两个操作
【发布时间】:2016-11-18 03:54:15
【问题描述】:

我目前正在学习 Node.js/JavaScript,以便使用 Discordie 库编写 Discord 机器人。

我有两个单独的操作,一个创建一个到服务器的邀请,另一个踢用户并向他们发送一条消息,如果他们在其中一条消息中使用了诽谤。

e.message.author.openDM().then(dm => dm.sendMessage(`You have been kicked from the **${e.message.guild.name}** server for using a slur. Please consider this a probation. When you feel that you are ready to not use that sort of language, feel free to rejoin us.`));
e.message.author.memberOf(e.message.guild).kick();

是我用来直接向用户发送消息然后踢他们的方法。我有一个单独的命令 (!invite) 生成邀请并从收到的 json 中提取邀请代码:

var generateInvite = e.message.channel.createInvite({"temporary": false, "xkcdpass": false});
generateInvite.then( function(res) { e.message.channel.sendMessage("https://discord.gg/" +res.code); });

我希望能够在直接消息代码中生成邀请,以便向被踢的用户发送邀请,如果他们可以避免再次使用那种语言,那么他们会回来,但是我不知道如何正确链接我的承诺:

generateInvite.then( function(res) { return res.code } ).then(e.message.author.openDM().then(function(dm){ dm.sendMessage(`You have been kicked from the **${e.message.guild.name}** server for using a slur. Please consider this a probation. When you feel that you are ready to not use that sort of language, feel free to rejoin us by following this link: https://discord.gg/` + res.code)}));

这个承诺链我哪里出了问题?

【问题讨论】:

  • “我的承诺链哪里出了问题?” 不应该包含 (.openMD() 来引用函数 openDM 并且不要立即调用函数,或e.message.author.openDM() 应该从匿名函数返回;目前似乎是语法错误?
  • 请缩进你的代码,单行很难看懂

标签: javascript node.js


【解决方案1】:

应该是

const author = e.message.author;
generateInvite.then( function(res) {
    author.openDM().then(function(dm){
        dm.sendMessage(`… link: https://discord.gg/${res.code}.`);
        author.memberOf(e.message.guild).kick();
    })
});

不要 return res.code 无处可去,也不要传递承诺 (openDM().then(…)) 来代替回调。

此外,您可能只想在向用户发送消息后踢用户,因此请确保这两个操作的顺序正确。

您可能还想考虑并行创建邀请和打开 dm 频道,使用 Promise.all 等待两个承诺,然后在单个回调中使用它们的结果。

【讨论】:

  • 谢谢! 踢之前对 DM'ing 进行良好的调用。现在我知道如何处理未来的承诺了:)
猜你喜欢
  • 1970-01-01
  • 2020-12-08
  • 2020-10-10
  • 2015-12-22
  • 2015-01-07
  • 2021-11-23
  • 1970-01-01
  • 2014-08-05
  • 2015-12-21
相关资源
最近更新 更多