javascript - 链接 promise 执行两个操作

标签 javascript node.js

我目前正在学习 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); });

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

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

这个 promise 链哪里出了问题?

最佳答案

应该是

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

不要将 res.code 返回到任何地方,并且不要在回调的位置传递 Promise (openDM().then(…)) .

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

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

关于javascript - 链接 promise 执行两个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387617/

相关文章:

javascript - 在原型(prototype)对象 Javascript 中引用 html 元素

javascript - 从引导模式获取图像 URL 到 javascript

node.js - ExpressJS 和 MongooseJS : can I query array values in a subdocument?

node.js - 如何在 Jest 的自定义测试环境文件中使用 TypeScript?

javascript - Node JS/MongoDB 中的嵌套查询

node.js - 将 Async/Await 与 node-postgres 一起使用

node.js - 如何在nodejs模型中获取用户ip?并在我的表格列 ip_address 中更新

javascript - jQuery:addClass 仅一次

javascript - 如何使我的网页加载速度更快?

javascript - 设置动态创建的 iframe 的基本标记