首页 > 解决方案 > 如何调用异步函数并阻止所有其他协程直到它完成?

问题描述

我有一个不和谐的机器人,在它的on_connect功能中,我循环并检查机器人的 MongoDB 数据库(例如,检查在它停机时加入的新公会)。那段代码如下所示:

# inside the client class
async def on_connect(self):
    await self.init_database()  # I need this to block everything

    # ...

async def init_database(self):
    # loop through everything in the db with a custom data manager that uses Motor to connect
    # with MongoDB (requires async/await).
    # takes ~1 minute to run if I don't block other coroutines.

有什么办法可以阻止所有其他协程直到init_database完成运行?

编辑:我刚刚意识到,如果我不让所有的协程都在init_database阻塞中,那么只有init_database阻塞是没有用的。如果我可以在一个 coro 阻塞中制作所有 coros,那将是最好的,否则我将不得不同时使用 PyMongo 和 Motor。

标签: pythonasynchronousasync-awaitpython-asyncio

解决方案


推荐阅读