Python异步与Node.js异步:如何实现Python异步函数非阻塞执行?
问题描述
我分别用Node.js和Python asyncio实现了异步脚本:
Node.js实现代码
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function get_burgers() { console.log("Just ordered..."); console.log("Making burgers"); await sleep(3000); console.log("Burgers ready!"); console.log("Eating them..."); } async function main() { console.log("Walking into restaurant..."); console.log("Ordering..."); get_burgers(); console.log("Talking, talking, talking..."); } main();
Node.js代码输出
Walking into restaurant... Ordering... Just ordered... Making burgers Talking, talking, talking... Burgers ready! Eating them...
Python asyncio初始实现代码
import asyncio async def get_burgers(): print("Just ordered...") print("Making burgers...") await asyncio.sleep(5) print("Burgers ready!") print("Eating burgers") async def main(): print("Walking into store with crush") print("Ordering....") await asyncio.gather(get_burgers()) print("Talking, talking, talking...") asyncio.run(main())
当前Python脚本会阻塞后续代码,导致“Talking, talking, talking...”最后打印;若去掉await asyncio.gather前的await则会报错。如何修改Python脚本,使其输出效果与Node.js版本一致?
解决方案
要实现和Node.js一致的非阻塞效果,只需创建异步任务但不立即等待,让事件循环在执行后续代码的同时后台处理异步任务。修改后的Python代码如下:
import asyncio async def get_burgers(): print("Just ordered...") print("Making burgers...") await asyncio.sleep(5) print("Burgers ready!") print("Eating burgers") async def main(): print("Walking into store with crush") print("Ordering....") # 创建异步任务提交给事件循环,不阻塞后续代码执行 asyncio.create_task(get_burgers()) print("Talking, talking, talking...") asyncio.run(main())
逻辑说明
- Node.js中直接调用
get_burgers()会生成一个未被await的Promise,事件循环会在后台处理这个异步任务,同时继续执行后续代码。 - Python里对应的操作是用
asyncio.create_task()把协程包装成任务,交给事件循环调度。这样main()函数不会卡在get_burgers()处,会直接执行后续打印语句,而get_burgers()会在后台等待sleep完成后继续执行剩余逻辑。
内容的提问来源于stack exchange,提问作者RogerKint
相关产品推荐
相关产品推荐

