简体   繁体   English

返回承诺的结果

[英]Returning the result of a 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
          })
        })
     })
  })
}

How do I return the chatRoom object, which is a result of nested promises, to the main function? 如何将嵌套承诺的结果chatRoom对象返回给主函数?

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

This is for getting idea. 这是为了获得想法。 You need to use reject too. 您还需要使用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
          })
        })
     })
  })
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM