【问题标题】:How to iterate over an array and constructing an object from the results of a PostgreSQL query如何遍历数组并从 PostgreSQL 查询的结果构造对象
【发布时间】:2020-03-24 03:10:25
【问题描述】:

这是我的问题:

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

我希望输出看起来像这样:

{
    t_H1: [ [pName: "P1", pPrice: 0.5], [pName: "P2", pPrice: 1.2] ],
    t_H2: [ [pName: "P1", pPrice: 0.6], [pName: "P2", pPrice: 1.0] ]
}

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

{}

【问题讨论】:

    标签: arrays node.js json postgresql


    【解决方案1】:

    forEach 循环不会等待承诺直到它们被解决,这就是为什么

    console.log(jOut);

    在您的所有/任何承诺得到解决之前立即执行。

    改为使用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);
    
    
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多