我们怎么能知道所有的异步操作,所有的回调都完成了,并等待它们

How can we know that all asynchronous operations, all callback are done, and wait for them

本文关键字:等待 怎么能 异步操作 我们 回调      更新时间:2023-09-26

以下代码,读取具有按类别排序的文档和值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);
}); 

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

我怎么知道所有异步操作和所有回调都完成了,并等待它们呢。我读过关于"承诺"的文章,但用它写一些高效干净的东西看起来很糟糕。

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

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

谢谢。

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

在启动最后一个ajax调用后,在超时后启动观察程序进程,在执行任何操作之前检查window.open_procs是否等于0。

绝对建议学习Promises。在本例中,Promise.all()是您要查找的方法,用于在Promise数组全部完成时注册回调。

npm上有一些mongodb客户端包装库可以自动承诺MongoClient请求:

  • https://github.com/Submersible/node-magnolia
  • https://www.npmjs.com/package/mongodb-promise

相关:http://taoofcode.net/promise-anti-patterns/