asyncio future

asyncio future


1. Future Object

class asyncio.Future(*, loop=None)
Future代表一段异步操作的最终结果。非线程安全。
它是awaitable对象。

1.1. 常用方法

  1. result() 返回结果
    正常返回结果有两个条件,done/有一个结果(使用set_result()设定)。
    如果done但是有异常(set_exception()设定),raises the exception.
    如果对象被取消raises a CancelledError exception.
    如果没完成,raises a InvalidStateError exception.

  2. set_result(result):标定对象为done并设置结果。
    如果已经done,Raises a InvalidStateError。

  3. set_exception(exception):标定对象为done并设置异常
    如果已经done,Raises a InvalidStateError。

  4. done():是否done。意为它经过以下之一方法处理,cancelled/set_result()/set_exception()

  5. cancelled():是否已取消。通常在设置结果或异常前检查。

  6. add_done_callback(callback, *, context=None):添加回调
    回调函数的唯一参数是Future本身。
    回调由loop.call_soon()调用。
    如果想用更多参数,unctools.partial()。

  7. remove_done_callback(callback)
    Remove callback from the callbacks list.
    Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.

  8. cancel():取消future和回调。
    如果它已经done或取消,返回False。否则,执行操作并返回True。

  9. exception():返回异常。
    只能在done状态下返回。
    已取消raises a CancelledError exception.
    未doneraises an InvalidStateError exception.

  10. get_loop():返回loop

posted @ 2020-05-13 21:28  木林森__𣛧  阅读(260)  评论(0)    收藏  举报