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


如何将嵌套承诺的结果chatRoom对象返回给主函数?

最佳答案

不要忘记退还诺言以便被束缚。

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

09-27 16:18