以下是一个示例代码,用于遍历异步任务以更新用户角色:
import asyncio
async def update_user_role(user):
# 模拟更新用户角色的异步任务
await asyncio.sleep(1)
print(f"Updated role for user {user}")
async def process_users(users):
tasks = []
for user in users:
task = asyncio.create_task(update_user_role(user))
tasks.append(task)
await asyncio.gather(*tasks)
async def main():
users = ["user1", "user2", "user3"]
await process_users(users)
asyncio.run(main())
在这个示例中,update_user_role
函数模拟了一个异步任务,用于更新用户角色。process_users
函数遍历用户列表,并为每个用户创建一个异步任务,并将其添加到任务列表中。然后,使用asyncio.gather
方法将所有任务同时运行。最后,通过调用asyncio.run(main())
来运行主函数。
当运行这个示例代码时,它将输出类似于以下内容:
Updated role for user user1
Updated role for user user2
Updated role for user user3
这表明每个用户的角色已经被更新。请注意,由于异步任务是同时运行的,因此更新操作的顺序可能会有所不同。