How to break loop inside a promise?
Assuming you want to call the compare
s sequentially, this will do it:
.then(function(answers) {
var compare = Promise.promisify(bcrypt.compare),
i = 0;
return Q(false).then(function checkNext(res) {
return res ||
i<answers.length && compare(answers[i++].password, user.password)
.then(checkNext);
});
})
It will "recursively" step trough the answers
array, stopping on the first true
result. To return the correct answer (instead of just true
for "found") or null
(if not found) like @Noseratio's code, you could use
var i = 0, answer;
return Q(false).then(function checkNext(res) {
return res ? answer : (i<answers.length || null) && compare((answer = answers[i++]).password, user.password).then(checkNext);
});
or better the more verbose
function next(i) {
if (i < answers.length)
return compare(answers[i].password, user.password).then(function(res) {
return res ? answers[i] : next(i+1);
});
else
return null;
}
return next(0);