You need to enable JavaScript to run this app. Python中什么功能等价于JavaScript的Promise.all()?
优惠活动
大模型
产品
解决方案
定价
更多

Python中什么功能等价于JavaScript的Promise.all()?

Python 中实现 JavaScript Promise.all 等价效果的方案

首先纠正认知误区:你观察到的执行顺序固定,不代表没有并发运行。JavaScript 的Promise.all本质是单线程事件循环下的IO密集型并发,并非多CPU并行,Python asyncio的运行逻辑和JS完全一致。你当前的测试出现固定执行顺序,是因为你的两个测试函数都是纯同步打印逻辑,没有任何异步IO阻塞点,协程一旦被调度就会直接执行完成,不会让出事件循环,才会出现固定的调度顺序。

1. IO密集型场景:使用asyncio.gather()(完全等价Promise.all)

Python asyncio 中内置的asyncio.gather()就是和Promise.all行为完全一致的API:

  • 接收多个协程作为参数,并发调度执行
  • 所有协程执行完成后,返回和传入顺序一致的结果列表
  • 任意一个协程抛出异常,都会直接整体抛出异常,和Promise.all的报错逻辑一致

修正后的代码示例

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

# 原代码重复初始化client,第一行discord.Client()是冗余的,直接用commands.Bot即可
client = commands.Bot(command_prefix='!')

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

async def bar():
    # 加入模拟异步IO的等待逻辑,触发协程切换,就能看到并发调度效果
    await asyncio.sleep(random.random() * 2)
    print("sjj")
    return "bar 执行结果"

async def ba():
    await asyncio.sleep(random.random() * 2)
    print("dhhdh")
    return "ba 执行结果"

@tasks.loop(seconds=5)
async def promise():
    # asyncio.gather 等价于 Promise.all
    results = await asyncio.gather(bar(), ba())
    # 结果顺序和传入协程的顺序一致,和实际执行顺序无关
    print(results)

如果用上述带随机sleep的代码测试,会发现两个函数的打印顺序是随机的,符合并发执行的特征。

2. CPU密集型场景:使用进程池实现真正并行

如果你要执行的是CPU密集型计算任务,单线程事件循环的并发无法利用多核CPU性能,需要真正的多CPU并行,可以用concurrent.futures.ProcessPoolExecutor实现:

import concurrent.futures

def cpu_task1():
    # 进程池执行的是普通同步函数,不能是async协程
    print("任务1执行")
    return "task1 结果"

def cpu_task2():
    print("任务2执行")
    return "task2 结果"

if __name__ == "__main__":
    # 最多同时启动2个工作进程
    with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
        # 提交任务到进程池,返回future对象
        f1 = executor.submit(cpu_task1)
        f2 = executor.submit(cpu_task2)
        # 等待所有任务完成获取结果,等价于Promise.all逻辑
        results = [f1.result(), f2.result()]
    print(results)

内容的提问来源于stack exchange,提问作者user15594988

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 09:54:05