Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
与节点js async/await相比,理解Python async/await_Python_Node.js_Asynchronous_Async Await - Fatal编程技术网

与节点js async/await相比,理解Python async/await

与节点js async/await相比,理解Python async/await,python,node.js,asynchronous,async-await,Python,Node.js,Asynchronous,Async Await,我正在学习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

我正在学习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();
节点结果正是我所期望的。我的理解是,
create_task
创建的任务在等待它们之前(在for循环中)不会开始执行;但是,如果第一个任务尚未完成,for循环如何前进以开始执行第二个任务


谢谢你在这一点上的帮助

我的困惑是因为没有意识到
创建任务
是用来完成任务的。可以修改Python代码,以便通过省略
create_任务
而只是等待任务来给出节点结果:

async def main():

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

使用
create_task
与使用
Promise类似。Node.js中承诺数组上的所有

请注意,如果在Node.js版本中,首先创建“task”(
Promise
),将其添加到数组中,然后在循环中等待,结果将是相同的。感谢您的深入了解。我认为这种差异与以下事实有关:节点内的承诺是“渴望的”
async def main():

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