10
ようawaitablesを組み合わせ、それを並列にタスクを実行し、Promise.all
を使用して完了するために、それらのすべてを待つことは簡単です:は非同期JavaScriptで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で、後者を書き換えることを試みた:
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()
しかし、私のタスクは順番に実行されます。
複数の待ち受けを待つ最も簡単な方法は何ですか? 私のアプローチはなぜ機能しませんか?
あまりにもasyncio.gatherに言及してください –
'wait'は' timeout'引数を許す 'wait'と' gather'の主な違いはありますか? –