NodeJS asynchronous functions. How to do A and B then C?
-
20-12-2019 - |
Question
I wrote the following code and tested it successfully on the mongo console.
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;
I am now trying to implement it in nodejs... but I don't think I am getting it right
I started like this :
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);
How do I tell geoqueries() that the upParts and downParts find queries are finished ?
Solution
Try using Promises.
http://howtonode.org/promises is one of the best resources about.
You can do a chain of promises. Something like:
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();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow