本文介绍了结合诸如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?

推荐答案

等效项将使用 asyncio.wait :

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()

因为当您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之类的等待者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 12:37