Python 异步编程的问题 Asyncio ?-灵析社区

UX_siri

我发现 `await` 并没有用 `update_product_loop` 还是立刻就执行力,那 `await` 和 `async` 的到底是什么含义,以及我要怎么才能做到真正的等 异步任务 `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())

阅读量:17

点赞量:0

问AI
# 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']