I am still quite new to writing code for Node.js (coming from PHP) and sometimes struggle to understand if async operations are working correctly, especially when there are multiple nested database calls/async operations.
For example, in this piece of code (which uses mongo), will the program only finish when deleted
has been set on any required accounts? (see todo
1, 2 and 3):
// array of account emails to be compared against the accounts already in the database (using `email`)
var emailsArray;
accountsDatabase.find({}, {})
.then(function (accountsInDB) {
return q.all(_.map(accountsInDB, function (dbAccount) {
// compare account's email in db with emails array in memory using .email
if ((emailsArray.indexOf(dbAccount.email) > -1) === false) {
// todo 1. should there be another 'then' here or is 'return' ok in order for it to work asynchronously?
return accountsInDB.updateById(dbAccount._id, {$set: {deleted: true}});
} else {
// todo 2. is this return needed?
return;
}
}));
})
.then(function () {
// TODO 3. WILL THE PROGRAM POTENTIALLY REACH HERE BEFORE `deleted` HAS BEEN SET ON THE REQUIRED ACCOUNTS?
callback(); // all of the above has finished
})
.catch(function (err) {
callback(err); // failed
});