【发布时间】:2021-01-18 12:32:33
【问题描述】:
我正在学习 Python 中的异步编程。我写了一些代码来模拟在 Python 和 Node 中获取 url;结果不同,我不知道为什么。
Python
async def asyncFunc():
await asyncio.sleep(3)
print('woke up...')
async def main():
tasks = [asyncio.create_task( asyncFunc() ) for i in range(3)]
for task in tasks:
await task
print('done waiting...')
asyncio.run(main())
结果:
woke up...
woke up...
woke up...
done waiting...
done waiting...
done waiting...
节点
const asyncFunc = async () => {
await mySleepFunction(3);
console.log('woke up...');
}
const main = async () => {
for (let i = 0; i < 3; i++) {
await asyncFunc();
console.log('done waiting...');
}
}
main();
结果
woke up...
done waiting...
woke up...
done waiting...
woke up...
done waiting...
Node 结果符合我的预期。我的理解是 create_task 创建的任务在等待(在 for 循环中)之前不会开始执行;但是如果第一个任务尚未完成,for 循环如何提前开始执行第二个任务?
感谢您对此的帮助
【问题讨论】:
-
请注意,如果您在 Node.js 版本中首先创建“任务”(
Promise),将其添加到数组中,然后循环等待它,结果将是一样。 -
感谢您的洞察力。我认为这种差异与 Node 中的承诺是“渴望的”这一事实有关。
标签: python node.js asynchronous async-await