2
我有一個異步函數返回一個隨機的學生。現在我想要一個返回兩個獨特學生的函數 - 我的問題的來源。node q promise遞歸
getTwoRandom = function(req) {
var deferred = Q.defer();
Q.all([
Student.getRandom(req),
Student.getRandom(req)
])
.then(function(students){
if(students[0]._id !== students[1]._id) { //check unique
deferred.resolve(students);
} else {
//students are the same so try again... this breaks
return getTwoRandom(req);
}
});
return deferred.promise;
};
再往我有這樣的事情:
getTwoRandom(req).then(function(students) {
//do what I want...
});
問題是,當我做return getTwoRandom(req);
的.then()
功能下降的線犯規火...這是返回不同的承諾,.then()
心不是使用?
困惑的B/C這不是返回一個承諾,讓我使用後續...?後續的代碼是什麼樣的? – jaredrada
你是什麼意思?它絕對會回報一個承諾。就像我上面描述的那樣,'Q.all'返回一個承諾,我們正在返回。 – Jakob
再往下看,你會完全像你自己描述的那樣使用它。 – Jakob