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

Python异步调用双外部API:首个响应触发单次回调实现方案

实现异步API调用:首个响应触发单次回调

嘿,这个需求很常见,咱们用Python的asyncio就能完美解决,核心思路就是只等待第一个完成的异步任务,触发回调后直接忽略另一个任务的结果。下面给你完整的实现方案:

核心思路拆解

  • 用asyncio创建两个异步API请求任务
  • 使用asyncio.wait()并指定return_when=FIRST_COMPLETED,只获取第一个完成的任务
  • 触发回调后,取消未完成的任务,避免不必要的资源消耗
  • 确保回调函数仅执行一次

完整代码实现

首先需要安装aiohttp(用于异步HTTP请求):

pip install aiohttp

然后是代码:

import asyncio
import aiohttp

def callback_function(response):
    print(f"回调触发,响应内容:{response[:100]}...")  # 示例操作,可替换为你的逻辑

async def fetch_api(session, url):
    """异步请求API的函数"""
    async with session.get(url) as response:
        return await response.text()

async def test_async():
    print('some')
    print('some2')
    
    # 定义两个要调用的API地址(替换成你的实际API)
    api_urls = [
        "https://api.example.com/endpoint1",
        "https://api.example.com/endpoint2"
    ]
    
    async with aiohttp.ClientSession() as session:
        # 创建两个异步任务
        tasks = [asyncio.create_task(fetch_api(session, url)) for url in api_urls]
        
        # 等待第一个任务完成
        done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        
        # 获取第一个完成的任务结果
        first_result = next(iter(done)).result()
        
        # 触发回调函数
        callback_function(first_result)
        
        # 取消剩余未完成的任务
        for task in pending:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                print(f"已取消未完成的API请求")

if __name__ == "__main__":
    asyncio.run(test_async())

关键细节说明

  • asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED):这行是核心,它会在任意一个任务完成后立即返回,返回值分为已完成的done集合和未完成的pending集合
  • 取消pending任务:必须主动取消,否则这些任务会继续在后台执行,浪费网络和计算资源
  • 回调函数的触发:拿到第一个任务的结果后直接调用callback_function,确保只执行一次

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:08:26