我的配料数组有什么问题吗?得到一个空数组

问题描述 投票:0回答:1

我目前正在开发一款烹饪应用程序,但在使用 API 时遇到了问题。

IngredientsController.get('/', async (req, res) => {
    let ingredients:Ingredient[] = []
    await pool.query({text:'SELECT * FROM Ingredients ORDER BY id'}, (error: Error, results: QueryResult) => {
        if (error) {
            throw(error);
        }
        for (let key in results.rows) {
            let ingredient:Ingredient = new Ingredient(Number(results.rows[key].id), results.rows[key].name);
            ingredients.push(ingredient);
        }
        res.status(200);
        res.json(ingredients);
    })
    console.log(ingredients)
    return res;
})

当我在浏览器上测试 API 时,我可以看到完整的成分列表。

我的问题是

console.log(ingredients)
指令显示一个空数组。

谁能告诉我我的控制器出了什么问题?

正如你在代码中看到的,我在代码中添加了await指令,但它仍然不起作用。 是因为我在查询函数中加载了数组吗?

node.js typescript postgresql express pg
1个回答
0
投票

更改您的

await

    await pool.query({text:'SELECT * FROM Ingredients ORDER BY id'}, (error: Error, results: QueryResult) => {
        if (error) {
            throw(error);
        }
        ...
    })

致:

try {
  const results = await pool.query('SELECT * FROM Ingredients ORDER BY id');
  console.log(results);
} catch (error) {
  console.error(error.message);
}

一旦你看到这个工作正常;添加循环结构;不过,我可能会映射

results.rows
来创建
ingredients
数组。

© www.soinside.com 2019 - 2024. All rights reserved.