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
console.log(jOut);
is immediately executed before all/any of your promises are resolved.
Instead use for..of
loop
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.