Python 异步编程的问题 Asyncio ?

作者站长头像
站长
· 阅读数 19

我发现 await 并没有用 update_product_loop 还是立刻就执行力,那 awaitasync 的到底是什么含义,以及我要怎么才能做到真正的等 异步任务 a 完成再去其它呢,就是说 a 里有很多子任务是异步的

async def main():

    for page in JDServer.api("api/product/getPageNum"):
        if products_insert_on:
            await recursion_products_init(page["page_num"])
            update_product_loop()

        if category_insert_on:
            recursion_sync_category(page["page_num"])


    async with asyncio.TaskGroup() as tg:
        tg.create_task(update_product_category())
        tg.create_task(update_products_price())


asyncio.run(main())
回复
1个回答
avatar
test
2024-06-25
# Modifying the main function to use asyncio.gather instead of TaskGroup
async def main_modified():
    results = []
    
    for page in JDServer.api("api/product/getPageNum"):
        if True:  # Mocking products_insert_on as always True for testing
            result = await recursion_products_init(page["page_num"])
            results.append(result)
    
    # Ensure all recursion_products_init are done before executing update_product_loop
    if True:  # Mocking products_insert_on as always True for testing
        results.append(update_product_loop())

    if True:  # Mocking category_insert_on as always True for testing
        for page in JDServer.api("api/product/getPageNum"):
            result = await recursion_sync_category(page["page_num"])
            results.append(result)

    # Using asyncio.gather to run tasks concurrently
    result1, result2 = await asyncio.gather(update_product_category(), update_products_price())
    results.extend([result1, result2])

    return results

# Using the auxiliary function to execute the modified main coroutine
results_modified = await auxiliary_runner(main_modified())
results_modified

测试结果:RESULT


['Initialized products for page 1',
 'Initialized products for page 2',
 'Initialized products for page 3',
 'Updated product loop',
 'Synchronized category for page 1',
 'Synchronized category for page 2',
 'Synchronized category for page 3',
 'Updated product category',
 'Updated products price']
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容