如何处理嵌套promise的结果

时间:2016-06-04 00:12:00

标签: javascript bluebird botkit

我无法重构一些代码来使用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这根本没有帮助我

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

1 个答案:

答案 0 :(得分:2)

  

Promise.all允许我从一系列承诺中获得结果

Promise.all会返回一个承诺,一旦您在其中传递的所有承诺都得到满足,该承诺就会得到满足。 所以你需要做的是在它上面调用then

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