0

I'm having trouble refactoring some code to use Promises, this to avoid nesting callbacks, the code i'm trying to refactor looks like this:

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

I'm using botkit with the slack api, and bluebird for Promises.

The part of the code where I have the most trouble is with the loop that iterates through each id and starts a private conversation with a user; what i've been trying looks like this:

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

From what I understand, Promise.all allows me to get a result from an array of promises... however, I'm getting an error from this code: TypeError: this.task.bot.reply is not a function which isn't helping me at all.

How can I use promises to accomplish what I'm trying to do?

Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62

1 Answers1

2

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

Promise.all returns a promise that gets fulfilled once all the promises you passed in it are fulfilled. So what you need to do is to call then on it

Promise.all(parsedUserIds(userIdsGroup).map(function(id) {/*return promise here*/}))
.then(function(results) { console.log(results); })
Lev Denisov
  • 2,011
  • 16
  • 26