0

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?

stdob--
  • 28,222
  • 5
  • 58
  • 73
figuedmundo
  • 375
  • 1
  • 4
  • 15
  • The main problem here is my misunderstanding of the JavaScript Promises, I read http://www.html5rocks.com/en/tutorials/es6/promises/ but I don't get the solution to my problem. Please help! – figuedmundo Jun 08 '16 at 06:13
  • Please read the thread linked above, and if it's still unclear, Chapters 1-3 of this: https://github.com/getify/You-Dont-Know-JS/tree/master/async%20%26%20performance. Basically you need to use `id.map()` and `Promise.all()` to create multiple promises and get all of their results, then access the results inside a `.then()`. – JLRishe Jun 08 '16 at 06:23
  • 1
    Not sure why you even need a loop here at all. A simple `WHERE IN` would do: `db.any("SELECT * FROM dog WHERE id IN($1:csv)", [ids]) .then(function (data) { // got all your records; }); ` – vitaly-t Jun 08 '16 at 11:09
  • Thanks, that do the trick. – figuedmundo Jun 10 '16 at 00:00

0 Answers0