在Python中,什么等价于JavaScript promise.all()?

tf7tbtn2  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(166)

在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。

tgabmvqs

tgabmvqs1#

The answer by @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)])))

如果运行此脚本,您将看到输出为(特定小数可能会更改,barb可能会更改):

$ 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。

0x6upsns

0x6upsns2#

您可以使用asyncio.create_task
代码:

import asyncio
import time

async def bar():
    await asyncio.sleep(5)
    print("sjj")

async def ba():
    await asyncio.sleep(3)
    print("dhhdh")

async def promise():
    tasks = [asyncio.create_task(bar()), asyncio.create_task(ba())]
    for task in tasks:
        await task

asyncio.run(promise())

相关问题