【问题标题】:NodeJS problem getting multiple query results simultaneously?NodeJS问题同时获取多个查询结果?
【发布时间】:2022-01-25 06:25:05
【问题描述】:

这是我使用 NodeJS 的第一个项目,我正在尝试获取用户所属的所有组中的所有帖子。因此,我试图在调用 res.send 方法之前将所有数据放入数组中。但是,数组最后是空的(请原谅我使用法语的表命名)。

router.get('/getUserPostes/:userId', async (req, res) => {
    let userId = req.params.userId;
    let endResult = []
    await db.query('select groupeId from groupemembers where userId = ?', userId, async function(err, result){
        if (err){
            console.log(err.message)
            res.send(null)
        }
        else {
            await result.map(async groupe => {
                await db.query('select * from postes where groupeId = ?', groupe.groupeId, function(err, result){
                    if (result != []){
                        endResult.push(result)
                    }
                })
            })
            res.send(endResult)
        }
    })
})

【问题讨论】:

  • await result.map() 不会做你想做的事,因为你在等待一个数组(因为.map() 返回一个数组)而不是一个承诺。你可以做await Promise.all(result.map(...))
  • 另外,await db.query() 也没有做任何有用的事情,因为你也在传递一个回调。如果你传递一个回调,那么它不会返回一个承诺。请不要在不了解您如何准确地等待承诺的情况下到处塞满await,因为这是对await 唯一有用的东西。

标签: javascript mysql node.js arrays express


【解决方案1】:

函数.map 不是异步函数,因此您实际上是在.map 中的查询完成之前发送响应。假设您的数据库库支持承诺,这样的事情会更干净:

router.get('/getUserPostes/:userId', async (req, res) => {
  let userId = req.params.userId;
  try {
    const result = await db.query('select groupeId from groupemembers where userId = ?', userId)

    const endResult = await Promise.all(result.map(groupe => {
      return db.query('select * from postes where groupeId = ?', groupe.groupeId)
    }))
    res.send(endResult)
  } catch (err) {
    console.log(err.message)
  }
})

请记住,您可以使用一个查询来提取此数据。但是,如果不知道 DB 架构,我很难提供帮助。

【讨论】:

    【解决方案2】:

    await result.map() 没有做你想做的事,因为你在等待一个数组(因为.map() 返回一个数组)而不是一个承诺。您可以执行 await Promise.all(result.map(...)) 或更改为 for 循环和 await 每个单独的请求。

    另外,await db.query() 也没有做任何有用的事情,因为您还传递了一个回调。如果你传递一个回调,那么它不会返回一个承诺。请不要在不了解您如何准确地等待承诺的情况下到处塞满await,因为这是对await 唯一有用的东西。

    而且,如果这是 mysql,那么您将需要一个支持 Promise 的 mysql 的 nodejs 驱动程序,因此您可以这样做:

    router.get('/getUserPostes/:userId', async (req, res) => {
        const userId = req.params.userId;
        try {
            const endResult = [];
            const result = await db.query('select groupeId from groupemembers where userId = ?', userId);
            for (const groupe of result) {
                let groupResult = await db.query('select * from postes where groupeId = ?', groupe.groupeId);
                if (groupResult) {
                    endResult.push(groupResult);
                }
            }
            res.send(endResult);
        } catch (e) {
            console.log(err);
            res.sendStatus(500);
        }
    });
    

    要在 mysql 中使用 Promise,有多种方法可以获得 Promise 支持。一种方法是使用 mysql2 模块并执行以下操作:

    const mysql = require('mysql2/promise');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-26
      • 2011-03-06
      • 1970-01-01
      • 2021-11-19
      • 2011-04-28
      • 2021-04-29
      • 1970-01-01
      • 2017-01-06
      相关资源
      最近更新 更多