gpt4 book ai didi

javascript - 链接 promise 执行两个操作

转载 作者:行者123 更新时间:2023-12-03 06:32:29 25 4
gpt4 key购买 nike

我目前正在学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com