Created
January 6, 2018 13:59
-
-
Save hieunguyendut/47300e7890406228303471fc683b4342 to your computer and use it in GitHub Desktop.
problem with scope of variable callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAllCity(req, res) { | |
var promise = Q.fcall(function() { | |
return City.find({}, function(err, cities) { | |
if(err) { | |
console.log(err); | |
return res.send(404) | |
} | |
for (let i = 0; i < cities.length; i++) { | |
Location.findOne({_id : cities[i].locationId}, function(err, location){ | |
if(err) return; | |
cities[i].locationLng = location.lng; | |
cities[i].locationLat = location.lat; | |
}); | |
} | |
}); | |
}); | |
promise.then(function(data) { | |
console.log(data); | |
}, function(err) { | |
console.log(err); | |
}); | |
// return res.json({isSucess: true, data: cities}) | |
}; |
nghuuquyen
commented
Jan 6, 2018
•
function getAllCity(req, res) {
var promise = City.find({}, function(err, cities) {
if(err) {
console.log(err);
return res.send(404)
}
let tasks = [];
for (let i = 0; i < cities.length; i++) {
tasks.push(Location.findOne({_id : cities[i].locationId}, function(err, location){
if(err) return;
cities[i].locationLng = location.lng;
cities[i].locationLat = location.lat;
return cities[i];
}));
}
return Q.all(tasks);
});
promise.then(function(data) {
console.log(data);
}, function(err) {
console.log(err);
});
// return res.json({isSucess: true, data: cities})
};
function getAllCity(req, res) {
const promise = City.find().then(cities => {
let tasks = [];
for (let i = 0; i < cities.length; i++) {
tasks.push(Location.findOne({
_id : cities[i].locationId
})
.then(function(location){
cities[i].locationLng = location.lng;
cities[i].locationLat = location.lat;
return cities[i];
}));
}
return Q.all(tasks);
});
promise.then(cities => {
res.json({
isSucess : true,
data : cities
});
})
.catch(err => {
res.status(500).send({
message : err.message
});
});
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment