2016-08-19 7 views
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 
      }) 
     }) 
    }) 
    }) 
} 

ネストされた約束の結果であるchatRoomオブジェクトをメイン関数に戻すにはどうすればよいですか?約束の結果を返す

+0

「findOrCreate」と「spread」はどこから来たのですか? COTSかカスタムコードですか? – sp00m

+0

@ sp00m彼らは続編からです。両方とも約束を返す。 –

+0

あなたはそれを「返却」しません。あなたはそれを「待つ」。 –

答えて

4

を連鎖させるために約束を返すことを忘れないでください。

+0

これは正解です。ありがとうございました! –

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

いいえ、あなたは** **独自の約束を作成する必要はありません。それが「プロミス・コンストラクタ・アンチ・パターン」です。 –