【问题标题】:Understanding Python async / await compared with Node js async / await理解 Python async / await 与 Node js async / await 的比较
【发布时间】: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


【解决方案1】:

我的困惑来自于没有意识到create_task 被用于start coroutines running concurrently。可以修改 Python 代码,以便通过省略 create_task 而只是等待任务来提供节点结果:

async def main():

  for task in tasks:
      await asyncFunc()
      print('done waiting...')

使用create_task 类似于在Node.js 中对一组promise 使用Promise.all

【讨论】:

  • 请注意:考虑遵循 Python 编码指南,同时相应地使用 Python 和其他语言的指南。在 Python 世界中asyncFunc 的名字应该翻译成async_func
猜你喜欢
  • 2017-11-14
  • 2020-03-25
  • 2018-04-12
  • 2018-10-18
  • 2018-10-13
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多