如何从pg-promise获取和传播数据

时间:2016-06-08 05:48:00

标签: javascript promise pg-promise

我有以下输入数据:

ids = [1,2,3,4]

这是狗的一组id,我想使用pg-routing查询Dog表以获取所有狗的名字并返回如下的JSON对象:

{
  "breed": "Chow chow",
  "dogs": [
     {"id": 1, "name": "fluffy"},
     {"id": 2, "name": "pepe"},
     {"id": 3, "name": "tintin"},
     {"id": 4, "name": "cachirulo"}
  ]
}

我的代码:

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);

当我运行此代码时,控制台显示:

{
   "breed": "Chow chow",
   "dogs": []
}

DATA: {id: 1, name: "fluffy"}
DATA: {id: 2, name: "pepe"}
DATA: {id: 3, name: "tintin"}
DATA: {id: 4, name: "cachirulo"}

为什么会这样?我该如何解决?

0 个答案:

没有答案