返回承诺的结果

时间:2016-08-19 09:50:56

标签: javascript promise

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对象(嵌套承诺的结果)返回给main函数?

2 个答案:

答案 0 :(得分:4)

不要忘记返回承诺,以便链接

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

答案 1 :(得分:-1)

这是为了获得想法。您也需要使用reject

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