节点q保证recursion

我有一个asynchronous函数返回一个随机的学生。 现在我想要一个函数,返回两个独特的学生 – 我的问题的来源。

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()使用?

你已经过分复杂了很多:)

你可以这样做,而不是:

 getTwoRandom = function(req) { return Q.all([ Student.getRandom(req), Student.getRandom(req) ]).then(function(students) { if(students[0]._id !== students[1]._id) { return students; } else { return getTwoRandom(req); } }); }; 

现在,为什么这个工作? Q.all的结果总是一个新的承诺(不需要创build一个新的延期)。 无论你返回什么样的价值(ike students )都将被包裹在这个新的承诺中。 如果返回一个实际的承诺(如getTwoRandom(req) ),那么这个承诺将被返回。 这听起来像你想做的事情。