[英]How to iterate over an array and constructing an object from the results of a PostgreSQL query
Here's my problem:这是我的问题:
var ps = ["P1", "P2"];
var hs = ["H1", "H2"];
var jOut = {};
hs.forEach(async (h) => {
var t = `t_${h}`;
var query = {
text: `SELECT pName, pPrice FROM ${t} WHERE pName = ANY($1)`,
values: [ps],
rowMode: "array"
};
var qres = await client.query(query);
jOut[t] = qres.rows;
});
console.log(jOut);
I want the output to look something like this:我希望输出看起来像这样:
{
t_H1: [ [pName: "P1", pPrice: 0.5], [pName: "P2", pPrice: 1.2] ],
t_H2: [ [pName: "P1", pPrice: 0.6], [pName: "P2", pPrice: 1.0] ]
}
But instead my output looks like this:但相反,我的输出如下所示:
{}
forEach
loop doesn't wait for promises until they are resolved, that's why forEach
循环不会等待 promise 被解决,这就是为什么
console.log(jOut);
is immediately executed before all/any of your promises are resolved.在解决所有/任何承诺之前立即执行。
Instead use for..of
loop而是使用for..of
循环
for(const h of hs) {
var t = `t_${h}`;
var query = {
text: `SELECT pName, pPrice FROM ${t} WHERE pName = ANY($1)`,
values: [ps],
rowMode: "array"
};
var qres = await client.query(query);
jOut[t] = qres.rows;
}
console.log(jOut);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.