Android中如何用协程调用API?多API数据展示异常求助
修复API调用数据展示不稳定问题(协程实现方案)
你的核心问题是多API调用时没同步好请求生命周期,要么部分请求还没返回就提前处理数据,要么多个请求的结果互相覆盖,才会出现数据时有时无、展示不全的情况。用协程可以确保所有请求完成后再汇总数据,彻底解决这个问题,下面分两种常用环境给出实现方案:
1. Python环境(asyncio协程)
先排查原代码问题
你之前的通用API函数大概率是用同步请求但没控制执行顺序,或者用了异步却没等待所有任务完成,比如循环里丢请求但不等结果,导致数据收集不全。
协程实现代码
首先安装异步HTTP依赖:
pip install aiohttp
然后编写稳定的异步调用逻辑:
import asyncio import aiohttp # 异步API调用函数 async def fetch_api(session, url): async with session.get(url) as response: return await response.json() # 批量获取所有分类数据 async def get_all_category_data(): api_urls = [ "https://api.example.com/mobile", "https://api.example.com/shoes", "https://api.example.com/stationery" ] # 创建会话复用连接,提升请求效率 async with aiohttp.ClientSession() as session: # 生成所有异步任务 tasks = [fetch_api(session, url) for url in api_urls] # 等待所有任务执行完成,一次性获取全部结果 all_results = await asyncio.gather(*tasks) # 整理结果,按分类存储 category_data = {} for res in all_results: category_data[res["category"]] = res["items"] return category_data # 启动协程执行 if __name__ == "__main__": final_data = asyncio.run(get_all_category_data()) print(final_data)
关键说明
asyncio.gather(*tasks):强制等待所有API请求完成后才继续执行,从根源避免了“数据没返回就渲染”的问题。- 用
ClientSession复用连接:比每次创建请求更高效,也减少了网络异常概率。
2. JavaScript/Node.js环境(async/await)
如果是前端或Node.js项目,用Promise.all配合async/await同样能解决:
// 异步API请求函数 async function fetchApi(url) { const response = await fetch(url); return response.json(); } // 批量获取所有分类数据 async function getAllCategoryData() { const apiUrls = [ "https://api.example.com/mobile", "https://api.example.com/shoes", "https://api.example.com/stationery" ]; // 等待所有请求完成,收集全部结果 const allResults = await Promise.all(apiUrls.map(url => fetchApi(url))); // 整理分类数据 const categoryData = {}; allResults.forEach(res => { categoryData[res.category] = res.items; }); return categoryData; } // 调用并渲染数据(确保所有数据都已获取后再渲染) getAllCategoryData().then(data => { console.log(data); // 在这里执行数据渲染逻辑 });
关键说明
Promise.all会等待所有请求的Promise状态变为resolved,只有全部请求成功返回后才会进入下一步,保证数据完整。
内容的提问来源于stack exchange,提问作者Zankoo koochik
相关产品推荐
相关产品推荐

