2016-06-17 5 views
0

ログイン処理中にユーザーデータを取得しようとしています。 rethinkDbに格納されているデータ。 フローは次のとおりです。非同期操作をターゲットとするhttp要求を制御する方法

login: function (email, password, res) { 
     var feedback = daouser.get(email); 
     if (feedback.success) { 
      var user = feedback.data; 
      //Do some validatios... 
     }  
     res.status = 200; 
     res.send(feedback); 
    }, 

•要求がコントローラ•

は、コールハンドラ•dao.getを()正しいハンドラ

を選択(急行経由)コントローラに送られます•dao.get()コードは次のとおりです。

get: function (email) {   
    var feedback = new Feedback(); 
    self.app.dbUsers.filter({email: email}).run().then(function (result) { 
     var user = result[0]; 
     feedback.success = true; 
     feedback.data = user; 
     return feedback; 
    }); 
} 

実際の「その後」機能がコールされると、コントローラは、未定義フィードバック...私のデザインと間違っ

何かを取得する前に、電子コールあなたは...約束、dao.getリターン経由

+0

http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

答えて

1

var feedback = daouser.get(email);

です.getは非同期であるため、ここで同期割り当てを行うことはできません。また、.getから何も返されていないことに注意してください。それは未定義です。 私はこれをすべて約束しています。

get: function (email) {   
var feedback = new Feedback(); 

// RETURN is important here, this way .get() return a promise instead of undefined 
return self.app.dbUsers.filter({email: email}).run().then(function (result) { 
    var user = result[0]; 
    feedback.success = true; 
    feedback.data = user; 
    return feedback; 
}); 

}

login: function (email, password, res) { 
    //return the promise again, so login will be chainable too 
    return daouser.get(email) 
    // You can chain another then here, because you returned a promise from .get above 
    // Your then function will be called with the return from the previous then, which is 'feedback' 
    .then(function(feedback) { 
     if (feedback.success) { 
     var user = feedback.data; 
     //Do some validatios... 
     }  
     res.status = 200; 
     res.send(feedback); 
    } 
}, 
関連する問題