我有以下输入数据:
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"}
为什么会这样?我该如何解决?