I'm working with Promises in Node (also using Mongoose and Lodash) and I need to wait for a list of operations against the database to be ready and push the results to an array:
var users = [];
var email_to_id = function(email) {
return new Promise(function(resolve, reject) {
User.findOne({email: email}).exec().then(function(user, err) {
if (user) {
resolve(user);
} else {
reject(err);
}
});
});
};
_.each(emails, function(email) {
users.push(
email_to_id(email).then(function(user, err) {
if (user) {
return user;
} else {
// How not to return anything?
}
}).catch(next)
);
});
So far so good, however, if I pass a wrong email and email_to_id
rejects, the _.each
function will push a null
to the users
array.
How to prevent it from pushing null
? And instead not push anything.