0
function main() {
  matchUserToChatRoom(senderID)
    .then(function(chatRoom) {
      //FIXME: I want to be able to use chatRoom from the below function
      console.log(chatRoom)
    })
}

function matchUserToChatRoom(userId) {
  return models.User.findOne({where: {messenger_id: userId}})
    .then(function(user) {
       models.ChatRoom
        .findOrCreate({where: {status: "open"}, defaults: {status: "open"}})
        .spread(function(chatRoom, created) {
          chatRoom.addUser(user).then(function(chatRoom) {
            //FIXME: I want to use this "chatRoom" inside the main function
          })
        })
     })
  })
}

How do I return the chatRoom object, which is a result of nested promises, to the main function?

Maximus S
  • 10,759
  • 19
  • 75
  • 154

2 Answers2

4

Do not forget to return the promises in order to be chained.

function matchUserToChatRoom(userId) {
  return models.User.findOne({where: {messenger_id: userId}})
    .then(function(user) {
       return models.ChatRoom
        .findOrCreate({where: {status: "open"}, defaults: {status: "open"}})
        .spread(function(chatRoom, created) {
          return chatRoom.addUser(user);
        })
     })
  })
}
Ioan
  • 5,152
  • 3
  • 31
  • 50
-1

This is for getting idea. You need to use reject too.

function matchUserToChatRoom(userId) {
return new Promise(function(resolve, reject){
  models.User.findOne({where: {messenger_id: userId}})
    .then(function(user) {
       models.ChatRoom
        .findOrCreate({where: {status: "open"}, defaults: {status: "open"}})
        .spread(function(chatRoom, created) {
          chatRoom.addUser(user).then(function(chatRoom) {
             resolve(chatRoom);
            //FIXME: I want to use this "chatRoom" inside the main function
          })
        })
     })
  })
}
});
Ebrahim Pasbani
  • 9,168
  • 2
  • 23
  • 30
  • 1
    No, you **don't** need to create your own promise. That's the "promise constructor anti-pattern". –  Aug 19 '16 at 10:11