gpt4 book ai didi

python - 什么相当于 Python 中的 JavaScript promise.all()?

转载 作者:行者123 更新时间:2023-12-02 18:40:59 36 4
gpt4 key购买 nike

在 JavaScript 中我们可以使用 promise.all() 并行运行函数,但它在 python 中不存在,我如何在 Python 中并行运行两个函数?

import discord
import asyncio
from discord.ext import tasks, commands

client = discord.Client()
client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
print("Monitor Ativo!")
promise.start()
async def bar():
print("sjj")

async def ba():
print("dhhdh")

@tasks.loop(seconds=5)
async def promise():
await asyncio.wait([bar(), ba()])

但我注意到,当我运行函数时,它总是先运行最后一个函数,所以它不能并行运行,对吗?

因为它总是在第一个之前运行最后一个函数,所以它有一个模式,所以它不能并行运行,我如何在python中并行运行两个函数,相当于javascript中的promise.all .

最佳答案

The answer通过 @KetZoomer效果很好,但这里是如何使用更接近您想要的语法更轻松地扩展并正确返回返回值的方法:

import asyncio
import time

start_time = time.time()


async def bar():
await asyncio.sleep(10)
print(f"bar\ttotal time elapsed: {time.time() - start_time}s")
return 5


async def ba():
await asyncio.sleep(3)
print(f"ba\ttotal time elapsed: {time.time() - start_time}s")
return 19

async def b(num):
await asyncio.sleep(10)
print(f"b\ttotal time elapsed: {time.time() - start_time}s\tyour number was {num}")
return 2000


async def promise_all(funcs):
tasks = [asyncio.create_task(func()) for func in funcs]
return [await task for task in tasks]

print(asyncio.run(promise_all([bar, ba, lambda: b(5)])))

如果你运行这个脚本,你会看到输出是(特定的小数可能会改变,bar vs b 可能会改变):

$ py -3 banana.py
ba total time elapsed: 3.002803325653076s
bar total time elapsed: 10.00796914100647s
b total time elapsed: 10.00804877281189s your number was 5
Output: [5, 19, 2000]

注意:正如您在最后一个函数(b 函数)中看到的,如果您想传入一个变量,请使用 lambda。

关于python - 什么相当于 Python 中的 JavaScript promise.all()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68026637/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com