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

如何在箭头函数中存储数据?执行时遇Promise { undefined }错误

问题分析与修复方案

核心问题点

  • 异步操作未等待:用map执行异步箭头函数时,map直接返回Promise数组,但外层未通过await Promise.all()等待所有异步操作完成,导致函数提前结束返回undefined。
  • 变量重写冲突:循环里把存储函数的变量s重新赋值为Object.assign的结果,覆盖了原异步函数,后续调用会直接出错。
  • 无返回值:函数s内部没有返回最终处理结果,调用s()自然得到Promise { undefined }。
  • SQL注入风险:直接用字符串拼接SQL语句,存在严重安全漏洞。

修复后的代码

// 重命名变量避免覆盖原函数
let processData = async () => {
  const results = [];
  // 用for...of替代map,确保异步操作按顺序执行(需并行可改用Promise.all)
  for (const o of Object.values(sqlQuery)) {
    for (const k of a) {
      for (const l of c) {
        // 改用参数化查询规避SQL注入
        const district = `select slug from foa_section_content where foa_section_content_id IN (?)`;
        const [district1]: any = await connection.execute(district, [k]);
        
        const commune = `select slug from foa_section_content where foa_section_content_id IN (?)`;
        const [commune1]: any = await connection.execute(commune, [l]);
        
        // 生成新合并对象,不修改原o
        const mergedObj = Object.assign({}, o, { district1, commune1 });
        results.push(mergedObj);
      }
    }
  }
  // 返回最终处理结果数组
  return results;
}

// 调用函数并处理结果
processData().then(finalResult => {
  console.log(finalResult);
}).catch(error => {
  console.error(error);
});

// 若在async函数内调用,可直接用await
// const finalResult = await processData();

关键修改说明

  • 变量改名:将原s改为processData,避免循环中被覆盖。
  • 异步等待:用for...of确保每步异步操作完成后再执行下一步;需并行处理时,可把多层循环生成的Promise收集后用Promise.all等待。
  • 返回结果:新增results数组存储所有合并后的对象,函数最后返回该数组,调用后能拿到实际数据。
  • SQL安全:改用参数化查询,将k、l作为参数传入execute,彻底避免SQL注入。
  • 无副作用:Object.assign以空对象为第一个参数,生成新的合并对象,不修改原o的内容。

内容的提问来源于stack exchange,提问作者jaga b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:05:24