2014-11-04 60 views
0

以下代码 会读取文件,其中包含按类别排序的文档以及值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); 
}); 

问题是,当所有异步操作都结束了,我不知道。 读取过程可以先完成,或者更新过程可以先完成(如果在上次更新后有多个文档需要读取)。 所以我不知道何时关闭数据库。

我如何知道所有异步操作和所有回调都已完成,并等待它们。 我读到了关于“承诺”的内容,但是看起来像是用地狱来写一些高效而干净的东西。

我发现测试这一小段代码的唯一但不现实的方法是在最后添加一个等待循环。

异步功能似乎将一个非常简单的算法变成了一些深度困惑。

谢谢。

+0

有一个计数器初始化用零,在调用'.update()'之前增加它,并在更新回调中递减。零计数器==完成所有异步操作。 – 2014-11-04 22:59:03

+0

使用promises或'async'模块。 – SLaks 2014-11-05 15:13:41

回答

1

我想说你在window.open_procs = 0;中设置一个全局变量,然后在每次调用ajax调用开始时增加它,然后在每个ajax调用结果中执行的函数中减少它。

在您启动最后的ajax调用之后,启动您的watcher进程,超时时间会在执行任何操作之前检查window.open_procs等于0。