Commit b747fb73 authored by Nathan Graule's avatar Nathan Graule 💻
Browse files

Add Call.all() function

parent 319d33fe
from threading import Thread
from typing import Callable, Any, TypeVar, Optional
from typing import Iterable
__all__ = ['Call']
......@@ -103,6 +104,24 @@ class Call:
error = Exception(error)
return Call(lambda res, rej: rej(error))
@classmethod
def all(cls, calls):
# type: (Iterable[Call]) -> Call
"""Resolve a list of calls' resolved values, or fail with the first exception
:param calls: List of calls to resolve, in the same order than the Calls list"""
def func():
values = []
try:
for call in calls:
values.append(call.wait())
except Exception:
raise
return values
return Call.from_function(func)
@classmethod
def from_function(cls, func, *args, **kwargs):
# type: (Callable[[Any], T], *Any, **Any) -> Call
......
......@@ -2,6 +2,7 @@ from __future__ import print_function
import json
import os
import random
import time
import unittest
......@@ -84,3 +85,16 @@ class TestCall(unittest.TestCase):
self.assertNotEqual(value, 'org.sindresorhus.Caprine')
self.assertTrue(isinstance(value, Exception))
def test_all(self):
calls = []
for i in range(10):
def func():
time.sleep(2 + random.random())
return i
calls.append(Call.from_function(func))
results = Call.all(calls).wait()
for i in range(10):
self.assertEqual(results[i], i)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment