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

如何等待多个异步网络API调用完成后再执行后续代码?

如何等待多个异步API调用全部完成后再执行下一步?

不同编程语言都有对应的原生API来实现“等待多个异步任务全部完成”的需求,以下是几种主流技术栈的实现方案:

JavaScript/TypeScript

核心用Promise.all()来并行发起请求并等待所有结果返回:

// 模拟异步API调用(实际项目替换为真实fetch/axios请求)
const fetchData1 = () => fetch('https://api.example.com/data1').then(res => res.json());
const fetchData2 = () => fetch('https://api.example.com/data2').then(res => res.json());
const fetchData3 = () => fetch('https://api.example.com/data3').then(res => res.json());

async function handleAllRequests() {
  try {
    // 并行发起所有请求,等待全部完成
    const [result1, result2, result3] = await Promise.all([
      fetchData1(),
      fetchData2(),
      fetchData3()
    ]);
    // 所有请求成功完成后,执行后续逻辑
    console.log('所有API调用完成:', result1, result2, result3);
    // 这里写下一步操作,比如渲染数据、更新状态
  } catch (error) {
    // 只要有一个请求失败,会立即进入catch块
    console.error('某个API调用失败:', error);
  }
}

handleAllRequests();

如果需要容忍部分请求失败(即使个别请求出错,也要等待所有请求结束再处理),改用Promise.allSettled():

async function handleAllRequestsWithSettled() {
  const results = await Promise.allSettled([
    fetchData1(),
    fetchData2(),
    fetchData3()
  ]);
  
  // 逐个处理成功/失败的请求结果
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`请求${index+1}成功:`, result.value);
    } else {
      console.log(`请求${index+1}失败:`, result.reason);
    }
  });
  
  // 所有请求无论成败都完成后,执行下一步
  console.log('所有API调用已结束');
}

Python

基于asyncio和aiohttp实现,用asyncio.gather()管理异步任务:

import asyncio
import aiohttp

# 异步API调用函数
async def fetch_data(session, url):
    async with session.get(url) as response:
        return await response.json()

async def handle_all_requests():
    urls = [
        'https://api.example.com/data1',
        'https://api.example.com/data2',
        'https://api.example.com/data3'
    ]
    
    async with aiohttp.ClientSession() as session:
        # 创建所有异步任务,并行执行并等待全部完成
        tasks = [fetch_data(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        
        # 所有请求完成后执行后续逻辑
        print('所有API调用完成:', results)
        # 这里写下一步操作

# 运行异步主函数
asyncio.run(handle_all_requests())

如果需要忽略个别请求失败,给gather()加return_exceptions=True参数:

results = await asyncio.gather(*tasks, return_exceptions=True)
# 遍历结果区分成功与失败
for result in results:
    if isinstance(result, Exception):
        print('请求失败:', result)
    else:
        print('请求成功:', result)

Java

用CompletableFuture.allOf()实现异步任务的批量等待:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AsyncApiHandler {
    // 模拟异步API调用(实际替换为HttpClient等HTTP请求逻辑)
    private static CompletableFuture<String> fetchData(String url) {
        return CompletableFuture.supplyAsync(() -> {
            // 模拟网络延迟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "数据来自: " + url;
        });
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建多个异步任务
        CompletableFuture<String> future1 = fetchData("https://api.example.com/data1");
        CompletableFuture<String> future2 = fetchData("https://api.example.com/data2");
        CompletableFuture<String> future3 = fetchData("https://api.example.com/data3");

        // 等待所有任务完成
        CompletableFuture<Void> allTasks = CompletableFuture.allOf(future1, future2, future3);
        allTasks.get(); // 阻塞等待全部完成

        // 获取每个任务的结果
        String result1 = future1.get();
        String result2 = future2.get();
        String result3 = future3.get();

        System.out.println("所有API调用完成: " + result1 + ", " + result2 + ", " + result3);
        // 后续逻辑写在这里
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:42:49