结合诸如Promise.all之类的等待者 [英] Combine awaitables like Promise.all

查看:105
本文介绍了结合诸如Promise.all之类的等待者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在异步JavaScript中,很容易并行运行任务,并使用Promise.all等待所有任务完成:

In asynchronous JavaScript, it is easy to run tasks in parallel and wait for all of them to complete using Promise.all:

async function bar(i) {
  console.log('started', i);
  await delay(1000);
  console.log('finished', i);
}

async function foo() {
    await Promise.all([bar(1), bar(2)]);
}

// This works too:
async function my_all(promises) {
    for (let p of promises) await p;
}

async function foo() {
    await my_all([bar(1), bar(2), bar(3)]);
}

我试图用python重写后者:

I tried to rewrite the latter in python:

import asyncio

async def bar(i):
  print('started', i)
  await asyncio.sleep(1)
  print('finished', i)

async def aio_all(seq):
  for f in seq:
    await f

async def main():
  await aio_all([bar(i) for i in range(10)])

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

但是它会顺序执行我的任务.

But it executes my tasks sequentially.

等待多个等待对象的最简单方法是什么? 为什么我的方法行不通?

What is the simplest way to await multiple awaitables? Why doesn't my approach work?

推荐答案

等效项将使用

The equivalent would be using asyncio.wait:

import asyncio

async def bar(i):
  print('started', i)
  await asyncio.sleep(1)
  print('finished', i)

async def main():
  await asyncio.wait([bar(i) for i in range(10)])

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

为什么我的方法行不通?

Why doesn't my approach work?

因为当您await中的每个项目seq时,您将封锁该协程.因此,从本质上讲,您有伪装成异步代码的同步代码.如果您确实想要使用 ,则可以使用loop.create_taskasyncio.ensure_future来实现自己的asyncio.wait版本.

Because when you await each item in seq, you block that coroutine. So in essence, you have synchronous code masquerading as async. If you really wanted to, you could implement your own version of asyncio.wait using loop.create_task or asyncio.ensure_future.

编辑

如安德鲁所说,您还可以使用 asyncio.gather .

As Andrew mentioned, you can also use asyncio.gather.

这篇关于结合诸如Promise.all之类的等待者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆