You need to enable JavaScript to run this app. 如何在asyncio run_until_complete执行完成后运行后续代码
优惠活动
大模型
产品
解决方案
定价
更多

如何在asyncio run_until_complete执行完成后运行后续代码

问题解决

首先澄清一个认知误区:loop.run_until_complete()本身就是同步阻塞方法,会等待传入的所有异步任务全部执行完成后才会返回结果,并不会出现你以为的「后续逻辑在任务完成前就触发」的情况,你遇到的无限循环是待重试请求的索引映射逻辑错误导致的。


问题根因

你在更新repeat_queries时,使用全局结果列表的error_index(对应初始queries的索引)去索引当前轮次的repeat_queries,会导致永远拿到错误的待重试URL,甚至出现索引越界,因此永远无法得到正确结果,循环无法终止。


修复方案

方案1:直接修复现有循环逻辑

只需要调整repeat_queries的取值来源,每次从原始queries里取对应错误索引的URL即可:

repeat_queries = queries
error_index = list(range(len(repeat_queries)))
results = [None] * len(queries) # 初始化长度和queries一致的空列表,不要使用range生成的列表

while error_index:
    loop = asyncio.get_event_loop()
    repeat_results = loop.run_until_complete(fetch_all(repeat_queries, loop))
    # 将结果赋值到全局列表的对应位置
    for idx, res in zip(error_index, repeat_results):
        results[idx] = res
    # 重新计算错误索引
    error_index = [i for i in range(len(results)) if not isinstance(results[i], dict)]
    # 从原始queries取对应错误索引的URL,不要用当前repeat_queries做索引
    repeat_queries = [queries[i] for i in error_index]

方案2(更推荐):请求层内置重试逻辑,无需外层循环

直接修改fetch函数,给单个请求加重试次数限制,逻辑更简洁,也不会出现索引映射错误:

import aiohttp
import asyncio
import ssl
import nest_asyncio
nest_asyncio.apply()

MAX_RETRY = 3 # 单请求最大重试次数

async def fetch(session, url):
    retry_cnt = 0
    while retry_cnt < MAX_RETRY:
        try:
            async with session.get(url, ssl=ssl.SSLContext()) as response:
                return await response.json()
        except Exception as e:
            retry_cnt += 1
            await asyncio.sleep(1) # 重试前加间隔避免触发限流
    # 超过重试次数返回错误标识,也可以根据需求抛出异常
    return {"error": f"请求{url}失败,重试{MAX_RETRY}次仍未成功"}

async def fetch_all(urls, loop):
    async with aiohttp.ClientSession(loop=loop) as session:
        return await asyncio.gather(*[fetch(session, url) for url in urls], return_exceptions=True)

if __name__ == '__main__':
    queries = [] # 替换为你的URL列表
    loop = asyncio.get_event_loop()
    results = loop.run_until_complete(fetch_all(queries, loop))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 11:54:02