如何渲染for循环中生成的promise 实现多动物食品查询结果展示
问题根因
你的代码存在两个核心错误导致无法正常渲染:
db.query是异步方法,返回Promise对象,你没有等待异步查询完成就执行了res.render,此时传入模板的results里存储的都是未完成的Promise,没有实际查询数据。- 你直接把Promise作为对象的键存储,对象的键会被强制转为字符串,完全不符合预期的数据结构设计。
修复后的后端代码
将路由处理函数改为async,使用await等待所有查询完成后再渲染模板:
router.get('/search', async (req, res) => { try { let { term } = req.query; // 处理输入,过滤空值避免无效查询 const terms = term.replace(/\s+/g, '').split(',').filter(Boolean); const results = []; const parentQueryBase = "SELECT * FROM animal_profiles WHERE code = :code LIMIT 1"; const childQueryBase = "SELECT * FROM food f JOIN animal_profiles a ON f.animal = a.animal WHERE a.code = :code"; for (const code of terms) { // 等待动物基础信息查询完成 const animalProfile = await db.query(parentQueryBase, { replacements: { code }, type: QueryTypes.SELECT }); // 未查到对应动物信息则跳过 if (!animalProfile.length) continue; // 等待对应食品列表查询完成 const foodList = await db.query(childQueryBase, { replacements: { code }, type: QueryTypes.SELECT }); // 整理为模板需要的结构 results.push({ animal: animalProfile[0].animal, species: animalProfile[0].species, food: foodList }); } // 所有查询完成后再渲染页面 res.render('my_view', { results }); } catch (err) { console.error('查询出错:', err); res.status(500).send('服务器内部错误'); } });
修复后的Handlebars模板
修正标签闭合问题,调整为你需要的输出结构:
<h1>搜索结果</h1> {{#each results}} <p>{{animal}} - {{species}}</p> <ul> {{#each food}} <li>{{food_name}}: {{food_price}}</li> {{else}} <li>暂无对应食品</li> {{/each}} </ul> {{else}} <p>No food available</p> {{/each}}
可选优化:并行查询提升速度
如果输入的动物关键词较多,你可以用Promise.all并行执行所有查询,减少整体等待时间:
// 把上面的for循环替换为以下代码 const queryTasks = terms.map(async code => { const animalProfile = await db.query(parentQueryBase, { replacements: { code }, type: QueryTypes.SELECT }); if (!animalProfile.length) return null; const foodList = await db.query(childQueryBase, { replacements: { code }, type: QueryTypes.SELECT }); return { animal: animalProfile[0].animal, species: animalProfile[0].species, food: foodList }; }); // 等待所有查询完成,过滤掉未命中的结果 const results = (await Promise.all(queryTasks)).filter(Boolean);
内容的提问来源于stack exchange,提问作者jam-butter-scone-tea
相关产品推荐
相关产品推荐

