【问题标题】:Return Map Row NULL返回映射行 NULL
【发布时间】:2020-05-20 09:26:23
【问题描述】:

我正在尝试从 mysql 查询映射一个 json 响应,但我收到 ho 响应:data: NULL

这是我的代码:

const audience = rows.map((row) => {
    db.query(CountAudiences, [row.campaign], function(err, count, fields) {
        if (err) throw err;
        console.log('Query result: ', count[0].audience);
        return {
            id: row.id,
            title: row.title,
            campaign: row.campaign,
            action: row.action,
            date: row.date,
            audiences: count[0].audience
        }
    });
});
res.json({
    count: rows.length,
    data: audience
})

回复:

{
   "count":1,
   "data":[
      null
   ]
}

你知道如何解决这个问题吗? 谢谢:)

【问题讨论】:

    标签: javascript mysql node.js express


    【解决方案1】:

    在您放置查询的代码中,因此它是异步命中。试试这个

     function getResponse(){
        let rows = [{ id: 1, title: 5 }, { id: 2, title: "ggg" }]
        const audience = rows.map(async (row) => {
          return new Promise((resolve,reject)=> {
           db.query(CountAudiences, [row.campaign], function (err, count, fields) {
            if (err) throw err;
            console.log('Query result: ', count[0].audience);
            resolve( {
                id: row.id,
                title: row.title,
                campaign: row.campaign,
                action: row.action,
                date: row.date,
                audiences: count[0].audience
              })
             })
            })
         });
    
         return Promise.all(audience) 
       }
    
      getResponse().then((reponseData)=>{
        res.json({
        count: rows.length,
        data: reponseData
      })
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多