I have the following entry data:
ids = [1,2,3,4]
That is an array of ids of dogs and I want query Dog table using pg-routing in order to get the name of all dogs and return a JSON object like following:
{
"breed": "Chow chow",
"dogs": [
{"id": 1, "name": "fluffy"},
{"id": 2, "name": "pepe"},
{"id": 3, "name": "tintin"},
{"id": 4, "name": "cachirulo"}
]
}
My code:
var dogs = [];
ids.forEach(function(id) {
db.any("SELECT * FROM dog WHERE id = $1", id)
.then(function(data) {
console.log("DATA:", data);
var dog = {
id: id,
name: data.name
};
dogs.push(dog)
});
}, this);
var res = {
breed: "Chow chow",
dogs: dogs
};
console.log(res);
When I run this code, the console shows:
{
"breed": "Chow chow",
"dogs": []
}
DATA: {id: 1, name: "fluffy"}
DATA: {id: 2, name: "pepe"}
DATA: {id: 3, name: "tintin"}
DATA: {id: 4, name: "cachirulo"}
Why is this happening? How I can address it?