I want to save 8 objects to a MongoDB database using Mongoose. When the last document is saved, I want to report (i.e. send an event) that all documents have been saved.
The way I'm doing it now is quite messy (especially for increasingly larger amounts of documents I want to save).
This is how I have it now (just for 4 people for this example). Is there a cleaner way you can recommend?
person1.save(function(err, result){
if (err) console.log(err);
else{
person2.save(function(err, result){
if (err) console.log(err);
else{
person3.save(function(err, result){
if (err) console.log(err);
else{
person4.save(function(err, result){
if (err) console.log(err);
else{
done();
}
});
}
});
}
});
}
});
A useful library to coordinate asynchronous operations is async
. In your case, the code would look something like this:
var people = [ person1, person2, person3, person4, ... ];
async.eachSeries(people, function(person, asyncdone) {
person.save(asyncdone);
}, function(err) {
if (err) return console.log(err);
done(); // or `done(err)` if you want the pass the error up
});
Using promises and Array.map()
const userPromises = persons.map(user => {
return new Promise((resolve, reject) => {
person.save((error, result) => {
if (error) {
reject(error)
}
resolve(result);
})
})
});
Promise.all(userPromises).then((results) => {
//yay!
//results = [first, second, etc...]
}, (error) => {
//nay!
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With