
异步编程中的 asyncio 的困惑
正如你所观察到的,在你的代码中,await 和 update_product_loop 并不是同步执行的,即使使用了 await。这是因为 update_product_loop 并未使用 async 声明,因此它只是一个常规的同步函数。
await 和 async 的作用如下:
为了让 update_product_loop 真正成为异步的,你需要使用 async 修饰它,并使用 asyncio.gather 将它与其他异步任务组合起来。以下是如何修改你的代码:
# Modifying the main function to use asyncio.gather instead of TaskGroup
async def main_modified():
# Initialize products for each page
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())
# Synchronize categories for each page
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())
# Printing the results
print(results_modified)通过这些修改,update_product_loop 将成为异步的,并且只有在所有初始化产品和同步类别的任务完成后才会执行。
以上就是Asyncio中await无效?如何正确实现异步任务并发执行?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号