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

async/await使用问题:如何等待批量API请求完成后再返回处理后的数组

问题根因
  • map回调函数没有返回getStreamingLink生成的Promise对象,导致items_withLinks初始就是全undefined的数组
  • 异步API请求没有全部执行完成就直接读取数组,此时streamingLink还未完成赋值
正确实现方案

用Promise.all等待所有异步请求执行完成后再处理结果:

// 从数据库取数组
const items = await client.db('database').collection('collection').find({}).toArray();

// map生成包含所有异步请求的Promise数组
const promiseArr = items.map(async (item) => {
  const response = await getStreamingLink(item.filename);
  item.streamingLink = response.result.link;
  return item;
});

// 等待所有请求完成,拿到赋值后的数组
const items_withLinks = await Promise.all(promiseArr);

console.log(items_withLinks); // 此时已经完成所有streamingLink赋值
可选优化点
  • 如果API有并发请求限制,可以引入并发控制工具避免触发接口限流
  • 如果需要兼容单个请求失败不影响整个数组返回,可以在单个请求里加异常捕获逻辑:
const promiseArr = items.map(async (item) => {
  try {
    const response = await getStreamingLink(item.filename);
    item.streamingLink = response.result.link;
  } catch (err) {
    // 单个请求失败时赋值默认值
    item.streamingLink = '';
    console.error(`获取${item.filename}的播放链接失败:`, err);
  }
  return item;
});

内容的提问来源于stack exchange,提问作者Hugo Perez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:06:05