Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

arrays - 如何遍历数组并根据PostgreSQL查询的结果构造对象(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:

(但是我的输出看起来像这样:)

{}
  ask by Ngelus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

forEach loop doesn't wait for promises until they are resolved, that's why

(forEach循环在解决承诺之前不等待承诺,这就是为什么)

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



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...