Future对象

官网:https://docs.python.org/zh-cn/3/library/asyncio-future.html?highlight=future#asyncio.Future

 

这个例子创建一个 Future 对象,创建和调度一个异步任务去设置 Future 结果,然后等待其结果:

import asyncio

async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())

 

相关文章:

  • 2021-10-10
  • 2021-11-02
  • 2021-08-17
  • 2023-03-18
猜你喜欢
  • 2021-11-02
  • 2022-01-26
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
相关资源
相似解决方案