how.wtf

Promise all in Python

· Thomas Taylor

In JavaScript, promise.all() returns a single promise given an iterable of promises. The returned promise is fulfilled when all the iterable promises are fulfilled. If one promise is rejected, the resulting promise is also rejected.

1try {
2  const values = await Promise.all([promise1, promise2]);
3  console.log(values); // [resolvedValue1, resolvedValue2]
4} catch (err) {
5  console.log(error); // rejectReason of any first rejected promise
6}

How to use promise.all() in Python

Python natively supports similar functionality to promise.all(). The method is named asyncio.gather().

 1import asyncio
 2
 3async def some_function():
 4	await asyncio.sleep(1)
 5	return 1
 6
 7async def main():
 8    values = await asyncio.gather(
 9        some_function(),
10        some_function()
11    )
12    print(values) # [1, 1]
13
14asyncio.run(main())

#python  

Reply to this post by email ↪