簡體   English   中英

異步函數調用異步生成器調用異步函數

[英]Async Function calling async generator calling async function

我如何解決這里的雞和蛋問題?

一個函數將返回生成器的第一個結果,該生成器必須從調用它的函數中收集數據。 這適用於一般代碼,但是一旦您在循環中拋出異步(我不想返回協程),它就會出錯。 我怎么無法返回協程function_one

代碼:

import asyncio

async def second_iterator(number):
    for x in range(number):
        yield await function_one(x)

async def function_one(number):
    if number > 2:
        return asyncio.run(second_iterator(number))

    await asyncio.sleep(1)
    return number

def main(number):
    print(asyncio.run(function_one(number)))

main(3)

錯誤:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    main(3)
  File "main.py", line 15, in main
    print(asyncio.run(function_one(number)))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Owner\Anaconda3\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "main.py", line 9, in function_one
    return asyncio.run(second_iterator(number))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 34, in run
    "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop

您的腳本中應該只有一個asyncio.run() 這是一個程序的入口點:

import asyncio


async def main():
    # all your code is here


if __name__ == "__main__":
    asyncio.run(main())

asyncio.run()是唯一一個啟動事件循環的阻塞操作,它管理所有協程和任務的執行。

請考慮閱讀一些有關asyncio教程,它可能會幫助您更快地實現目標:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM