You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

烹饪应用API问题:Ingredients数组console.log为空,await未生效

问题原因

你这段代码的核心问题是**await没起到作用**,加上异步执行顺序导致console.log输出空数组:

  • pool.query的回调版本不会返回Promise,所以你加的await根本没办法等待数据库查询完成
  • 代码执行顺序是:先初始化空数组,调用pool.query发起异步请求后,直接跳过回调执行console.log(ingredients),这时候数组还没被填充;等数据库查询完成,回调函数才会执行,填充数组并返回响应,所以浏览器能拿到结果,但控制台输出是空的
修复方案

方案1:用Promise版本的query(推荐)

大部分数据库连接池(比如pg)的query方法,不传回调时会返回Promise,这样await就能正常等待查询完成:

IngredientsController.get('/', async (req, res) => {
    try {
        let ingredients: Ingredient[] = [];
        // 直接await query返回的Promise,不用回调
        const results = await pool.query({text:'SELECT * FROM Ingredients ORDER BY id'});
        
        // 遍历结果转换为Ingredient实例
        for (const row of results.rows) {
            const ingredient = new Ingredient(Number(row.id), row.name);
            ingredients.push(ingredient);
        }
        
        console.log(ingredients); // 现在能正确输出填充后的数组
        res.status(200).json(ingredients);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: '数据库查询失败' });
    }
})

方案2:保留回调的情况下调整代码

如果一定要用回调,把console.log移到回调函数内部,确保数组填充后再执行:

IngredientsController.get('/', (req, res) => {
    let ingredients: Ingredient[] = [];
    pool.query({text:'SELECT * FROM Ingredients ORDER BY id'}, (error: Error, results: QueryResult) => {
        if (error) {
            console.error(error);
            return res.status(500).json({ error: '数据库查询失败' });
        }
        for (const row of results.rows) {
            const ingredient = new Ingredient(Number(row.id), row.name);
            ingredients.push(ingredient);
        }
        console.log(ingredients); // 移到回调内,此时数组已填充
        res.status(200).json(ingredients);
    });
})
额外优化点
  • 遍历数组时,用for...of代替for...in,避免遍历到数组的非索引属性
  • 可以用map方法简化转换逻辑,一行代码生成目标数组:
    const ingredients = results.rows.map(row => new Ingredient(Number(row.id), row.name));
    

内容的提问来源于stack exchange,提问作者Rémi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:32:37