我试图查看Python的async
和await
是否可以帮助我简化回调链。我仍在用Python学习async
和await
。
我有一个用于异步编程的现有接口类,以支持三个自定义实现。调用该接口看起来像这样:
def without_async(value):
p = MyFuture(lambda x: x * 2).then(lambda y: str(y))
p.evaluate(value)
return p.result
assert without_async(2) == '4'
MyFuture
与asyncio.Future或Promises/A+中定义的接口非常相似:
class MyFuture(Generic[T]):
def __init__(self, callback: Callable[[T], ...]=None):
self.result: T = None
self.callback = callback
self._next: MyFuture = None
def then(self, callback: Callable[[T], U]) -> MyFuture:
# Similar to Future.add_done_callback
self.callback = callback
self._next = MyFuture()
return self._next
def evaluate(self, result: T):
# similar to Future.set_result
self.result = result
self._next.evaluate(self.callback(self.result))
现在,有没有任何方法可以使用await
使语法更漂亮?如果是,怎么办?
也许与此伪代码相似?
class MyFuture(collections.abc.Awaitable):
def __await__(self): ...
def run_until_complete(future):
...
def wrap(x: T) -> MyFuture[T]:
...
async def with_async(value):
x = 2 * await wrap(value)
return str(await wrap(value))
assert run_until_complete(with_async(2)) == '4'