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

如何为嵌套的fetch API调用实现async异步处理?

解决两次Fetch的异步依赖问题

你完全不用靠setTimeout这种不靠谱的方式,fetch本身返回Promise,用下面两种方法就能确保第二次请求在第一次请求完成后再执行:

方法一:Promise链式调用

把第二次fetch直接放在第一次请求的then回调里,只有第一次请求成功拿到数据后,才会触发第二次请求:

var response1;
var response2;

function wantToAsync() {
  fetch('example.com/fetchSearch?search=' + searchString, {
    method: 'GET',
    headers: {
      'Authorization': 'KEY HERE',
    },
  })
  .then(response => response.json())
  .then(data => {
    response1 = data;
    // 第一次请求完成,发起第二次请求
    return fetch('example.com/fetchSearch2?search=' + response1, {
      method: 'GET',
      headers: {
        'Authorization': 'KEY HERE',
      },
    });
  })
  .then(response => response.json())
  .then(data => {
    response2 = data;
    // 这里可以处理最终得到的response2数据
  })
  .catch(error => {
    // 捕获两次请求中可能出现的错误
    console.error('请求出错:', error);
  });
}

方法二:async/await(更简洁直观)

用async标记函数,内部用await等待每个fetch完成,逻辑和同步代码差不多:

var response1;
var response2;

async function wantToAsync() {
  try {
    // 等第一次请求完成并解析JSON
    const firstResponse = await fetch('example.com/fetchSearch?search=' + searchString, {
      method: 'GET',
      headers: {
        'Authorization': 'KEY HERE',
      },
    });
    response1 = await firstResponse.json();

    // 用第一次的结果发起第二次请求
    const secondResponse = await fetch('example.com/fetchSearch2?search=' + response1, {
      method: 'GET',
      headers: {
        'Authorization': 'KEY HERE',
      },
    });
    response2 = await secondResponse.json();

    // 处理最终数据
  } catch (error) {
    console.error('请求出错:', error);
  }
}

重要提醒

  • 你之前用的setTimeout是固定延迟,不管第一次请求实际多久完成,到点就执行,网络慢的时候1秒不够,网络快的时候纯浪费时间,绝对不能用。
  • 上面两种方法都是跟着异步操作的实际完成状态走,完全可靠。
  • 一定要加catch处理错误,不然网络问题或接口出错会导致代码崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:01:03