python - 如何在异步方法中将结果存储在列表中?

标签 python asynchronous

我有以下方法为我生成数据:

async def fetch_url(self, video_id):
    data = await self.s3.generate_presigned_url(...video_id...)
    return data

def convert_to_json(self, data):
    loop = asyncio.get_event_loop()
    tasks = []
    urls = [row[0] for row in data]
    for url in urls:
        tasks.append(fetch_url(url))
    loop.run_until_complete(asyncio.gather(*tasks))
    loop.close()

如何将 fetch_url 的结果存储在某个列表中?

最佳答案

asyncio.gather :

… If all the tasks are done successfully, the returned future’s result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). …

也就是说,如果您等待收集的结果,您将获得已获取的数据的列表


run_until_complete :

Return the Future’s result, or raise its exception.

run_until_complete会返回结果gather,即获取到的数据列表。


存储的结果很简单:

...
all_data = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
return all_data

关于python - 如何在异步方法中将结果存储在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226402/

相关文章:

python - "TypeError: ' 模块 ' object is not callable"与 webdriver.chrome

python - 类型错误 : 'NoneType' object is not iterable

c# - 异步写入套接字线程安全吗?

reactjs - 使用react。具有异步获取请求的私有(private)路由器

java - 无法处理 AsyncTask 调用的方法中的异常

node.js - 当循环中调用异步函数时,Node.JS 将如何处理循环控制?

java - 动态规划-最大切割的杆切割问题和实际解决方案

python - (Python新手求助)getch?

python - 从 Web 服务器向客户端提供二进制文件

javascript - 如何从异步调用返回响应?