NodeJS异步函数。怎么办A和B然后C?

时间:2014-07-28 19:52:13

标签: javascript node.js asynchronous mongodb-query

我编写了以下代码并在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查找查询是否已完成?

1 个答案:

答案 0 :(得分:1)

尝试使用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();
});