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

JavaScript for循环未等待fetch请求完成就进入下一次迭代的解决方法

问题原因与解决方案

你的问题出在callApi函数里的Promise.all(arr.map(...))写法:arr.map会立刻为所有id创建并启动异步任务,这些任务会并行执行,所以各个id的请求会同时发起,自然不会按顺序等待前一个id的所有分页完成再处理下一个。

修正后的代码

async function fetchData(id){
  // 给res添加let声明,避免全局变量污染
  for(let i=1;;++i){
    let res = await fetch(`https://some-api/v1/products/${id}/data?page=${i}`,{/*headers here*/});
    res = await res.json();
    if(res.length===0) break;
    else{ /*do some work here and continue for next iteration*/ }
  }
}

async function callApi(){
  const arr = [/*list of id's here*/];
  // 用for...of循环实现串行执行
  for(const id of arr){
    await fetchData(id);
  }
}
callApi();

为什么这样有效?

for...of循环中,每次迭代的await fetchData(id)会暂停整个循环,直到当前id对应的所有分页请求全部完成(直到fetchData里的break触发),才会进入下一次迭代处理下一个id,完全符合你“必须等当前迭代完成再进行下一次”的硬性要求。

另外注意给fetchData里的res添加let声明,避免意外的全局变量污染问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:20:44