Assuming you want to call compare sequentially, this will do this:
.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" go through the answers array, stopping at the first true result. To return the correct answer (instead of true for "found") or null (if not found), for example, @Noseratio code, you can 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 more detailed
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);
Bergi
source share