【发布时间】:2016-05-06 00:25:56
【问题描述】:
我对为 Node.js(来自 PHP)编写代码还是很陌生,有时很难理解异步操作是否正常工作,尤其是当有多个嵌套的数据库调用/异步操作时。
例如,在这段代码中(使用 mongo),程序是否只有在任何所需帐户上设置了deleted 时才能完成? (见todo 1、2 和 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
});
【问题讨论】:
-
不要使用
callback参数,而应该return你产生的承诺。
标签: javascript node.js mongodb asynchronous promise