gpt4 book ai didi

javascript - 如何处理嵌套 Promise 的结果

转载 作者:行者123 更新时间:2023-12-02 14:33:41 25 4
gpt4 key购买 nike

我在重构一些代码以使用 Promises 时遇到问题,这是为了避免嵌套回调,我尝试重构的代码如下所示:

bot.api.users.list({}, function(err, teamData) {
if(err) {
bot.botkit.log("Couldn't fetch team data from API", err);
return;
}

var members = teamData.members;
var msgSender = _.find(members, function(member) { return member.id == message.user });

parsedUserIds(userIdsGroup).forEach(function(id) {
var msgReceiver = _.find(members, function(member) { return member.id == id });

bot.startPrivateConversation({ user: id }, function(err, conversation) {
if(err) {
bot.botkit.log("Couldn't initiate private conversation", err);
return;
}

var message = format("Hey {to}, {from} just requested a Pull Request Review, here's the link: {githubLink}, please go and check it out!",
{ to: msgReceiver.name,
from: msgSender.name,
githubLink: githubRepoUrl });

conversation.say(message);
});
});

我使用带有 slack api 的 botkit 和用于 Promises 的 bluebird。

代码中我遇到最多麻烦的部分是循环遍历每个 id 并开始与用户的私有(private)对话;我一直在尝试的看起来像这样:

  var usersList = Promise.promisify(bot.api.users.list);
var privateConversation = Promise.promisify(bot.startPrivateConversation);

usersList({}).then(function(data) {
var members = data.members;
var msgSender = findMember(members, message.user);

return Promise.all(parsedUserIds(userIdsGroup).map(function(id) {
var msgReceiver = findMember(members, id);

return privateConversation({ user: id }).then(function(conversation) {
var message = format("Hey {to}, {from} just requested a Pull Request Review, here's the link: {githubLink}, please go and check it out!",
{ to: msgReceiver.name,
from: msgSender.name,
githubLink: githubRepoUrl });
conversation.say(message);
});
}));
}).catch(function(err){
bot.botkit.log(err);
});

据我了解,Promise.all 允许我从一系列 promise 中获取结果...但是,我从此代码中收到错误: TypeError: this.task.bot.reply is不是一个对我没有任何帮助的函数

我如何使用 Promise 来完成我想要做的事情?

最佳答案

Promise.all allows me to get a result from an array of promises

Promise.all 返回一个 promise ,一旦您传入的所有 promise 都得到履行,该 promise 就会得到履行。所以你需要做的是调用then就可以了

Promise.all(parsedUserIds(userIdsGroup).map(function(id) {/*return promise here*/}))
.then(function(results) { console.log(results); })

关于javascript - 如何处理嵌套 Promise 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625110/

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