NodeJS异步函数.怎么做A, B,然后C

NodeJS asynchronous functions. How to do A and B then C?

本文关键字:然后 异步 函数 NodeJS      更新时间:2023-09-26

我编写了以下代码,并在mongo控制台上成功地进行了测试。

var up_results = db.upParts.find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [3, 5]}}}},{"_id":1, "features.properties.partID":1,"features.properties.connectedTo":1}).toArray();
var down_results = db.downParts.find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [-80, 30]}}}},{"_id":1, "features.properties.partID":1}).toArray();
var part_results = [];
for (i = 0; i < up_results.length; i++) {
    for (j = 0; j < up_results[i].features[0].properties.connectedTo.length; j++) {
        for (k = 0; k < down_results.length; k++) {
            if (down_results[k]._id == up_results[i].features[0].properties.connectedTo[j]) {
                part_results.push(db.parts.find({_id:{$in:[ObjectId(up_results[i].features[0].properties.partID)]}}));
            }
        }
    }
}
parts_results.length;

我现在试图实现它在nodejs…但我觉得我做得不对

我是这样开始的:

var up_results = null;
var down_results = null;
var part_results = [];
function geoqueries(callback) {
            self.db.collection('upParts').find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [3, 5]}}}}, {"_id": 1, "features.properties.partID": 1, "features.properties.connectedTo": 1}).toArray(function (err, document) {
                up_results = document;
            });
            self.db.collection('downParts').find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [-80, 30]}}}},{"_id":1, "features.properties.partID":1}).toArray(function(err, document2) {
                down_results = document2;
            });
            callback();
        }
function dosomething() {
    ...do something with up_results and down_results
}
geoqueries(dosomething);

如何告诉geoqueries() upParts和downParts查找查询已经完成?

尝试使用Promises。

http://howtonode.org/promises是关于。的最佳资源之一。

你可以做一连串的承诺。比如:

var promises = [];
var deferred = q.defer();
promises.push(deferred.promise);
self.db.collection('upParts').find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [3, 5]}}}}, {"_id": 1, "features.properties.partID": 1, "features.properties.connectedTo": 1}).toArray(function (err, document) {
    up_results = document;
    deferred.resolve();
});
var deferred_i = q.defer();
promises.push(deferred_i.promise);
self.db.collection('downParts').find({"features.geometry": {$geoIntersects: {$geometry: {type: "Point", coordinates: [-80, 30]}}}},{"_id":1, "features.properties.partID":1}).toArray(function(err, document2) {
    down_results = document2;
    deferred_i.resolve();
});
q.all(promises)
.then(function() {
    callback();
});