我在重构一些代码以使用 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);
});
});
我将 botkit 与 slack api 一起使用,并将 bluebird 用于 Promises。
我最麻烦的代码部分是循环遍历每个 id 并开始与用户的私人对话;我一直在尝试的看起来像这样:
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 允许我从一系列承诺中获得结果......但是,我从这段代码中得到了一个错误:TypeError: this.task.bot.reply is not a function
这根本没有帮助我。
我如何使用承诺来完成我想要做的事情?