[Python]异步回调函数

import asyncio
from functools import partial
from asyncio import Future


async def f1():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "f1"


def callback1(future: Future):
    print(future.result())
    print("我是f1的回调函数")


def callback2(t, future: Future):
    print(t)
    print(future.result())


async def main():
    task1 = asyncio.create_task(f1())
    task1.add_done_callback(callback1)
    # partial偏函数
    task1.add_done_callback(partial(callback2, "我是t参数"))
    await asyncio.gather(task1)


asyncio.run(main())

"""
1
2
f1
我是f1的回调函数
我是t参数
f1
"""
posted @ 2023-03-30 19:19  LeoShi2020  阅读(179)  评论(0编辑  收藏  举报