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

Node.js中map函数内调用API后返回空数组问题求助

问题解决:异步流处理导致返回空数组

问题原因

你的代码中,Promise.all仅等待了axios的GET请求完成,但没有等待流的pipe操作及后续的uploadToFirestore异步任务。response.data.pipe(concat(...))是基于回调的异步操作,外层的async函数在axios请求结束后就会resolve,此时流处理和上传还没完成,所以attachments数组还是初始的空数组。

修复方案

将流的处理逻辑包装成Promise,让每个file对应的Promise能够等待流读取、上传完成后再resolve,这样Promise.all就能正确等待所有异步操作结束。

修复后的完整代码

const processInboundEmailAttachment = async (files: any[]): Promise<any[]> => {
  const attachments = [];

  await Promise.all(
    files.map(async (file) => {
      try {
        const response = await axios.get(file.url, {
          headers: {
            Accept: "message/rfc2822"
          },
          auth: {
            username: "api",
            password: "api-key"
          },
          responseType: "stream"
        });

        if (response && response.data) {
          // 将流处理包装为Promise,等待流读取和上传完成
          await new Promise<void>((resolve, reject) => {
            response.data.pipe(concat(async (data) => {
              try {
                const mediaUrl = await uploadToFirestore(file["content-type"], data, file.name);
                attachments.push({
                  name: file.name,
                  url: mediaUrl,
                  id: uuidv4()
                });
                resolve();
              } catch (error) {
                console.log("err", error);
                resolve(); // 即使上传失败,也要resolve避免Promise.all挂起
              }
            })).on("error", (err) => {
              console.log("stream error", err);
              resolve(); // 流错误时同样resolve
            });
          });
        }
      } catch (err) {
        log.error(err);
      }
    })
  );

  return attachments;
};

const uploadAttachment = async () => {
  const attachment = await processInboundEmailAttachment(JSON.parse(attach));
  console.log("attachment", attachment);
};

app.get("/uploadAttachment", uploadAttachment);

关键改动说明

  • 用new Promise<void>包裹流的pipe操作,确保只有当流读取完成、上传(或失败)后,这个Promise才会resolve
  • 为流添加error事件监听,避免流出错导致Promise一直pending
  • 每个file的处理逻辑现在会完整等待所有异步步骤完成,Promise.all就能正确等待所有文件处理完毕,此时attachments数组已经被正确填充

内容的提问来源于stack exchange,提问作者Bhavya Ardeshana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:40:37