以下代码 会读取文件,其中包含按类别排序的文档以及值desc, ,并修改每个文档的最高值类别。我们如何知道所有异步操作,所有回调都已完成,并等待它们
下面的代码:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://WRKHAL02:27017/test', function(err, db) {
if(err) throw err;
function (cbUpdate(err,updated) {
if(err) throw " \n cbUpdate \n" + err;
console.log(" Successfully updated " + updated + " Document");
}
var theFile = db.collection("theFile");
var cursor = theFile.find({});
cursor.sort([["State",1],["Temperature",-1]]);
currentState = "empty";
cursor.each(function(err,doc) {
if(err) throw " \n -*- cursor.each error -*- \n" + err;
if (doc == null) {
console.log(" \n doc == null ; End Of File \n ");
here use to be the db.close();
}
else {
if (currentState != doc.State) {
console.log(doc._id);
console.log(doc.State);
console.log(doc.Temperature);
var myquery = {};
myquery['_id'] = doc['_id'];
var myupdate = {$set:{"month_high":true}};
theFile.update(myquery, myupdate, cbUpdate);
currentState = doc.State;
}
}
});
setTimeout(function() {
console.log(" TimeOut ");
db.close();
}, 3000);
});
问题是,当所有异步操作都结束了,我不知道。 读取过程可以先完成,或者更新过程可以先完成(如果在上次更新后有多个文档需要读取)。 所以我不知道何时关闭数据库。
我如何知道所有异步操作和所有回调都已完成,并等待它们。 我读到了关于“承诺”的内容,但是看起来像是用地狱来写一些高效而干净的东西。
我发现测试这一小段代码的唯一但不现实的方法是在最后添加一个等待循环。
异步功能似乎将一个非常简单的算法变成了一些深度困惑。
谢谢。
有一个计数器初始化用零,在调用'.update()'之前增加它,并在更新回调中递减。零计数器==完成所有异步操作。 – 2014-11-04 22:59:03
使用promises或'async'模块。 – SLaks 2014-11-05 15:13:41