Understanding Python async / await compared with Node js async / await

Viewed 1721

I'm learning asynchronous programming in Python. I wrote some code to simulate fetching urls in Python and Node; the results are different and I'm not sure why.

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())

results:

woke up...
woke up...
woke up...
done waiting...
done waiting...
done waiting...

Node

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();

results

woke up...
done waiting...
woke up...
done waiting...
woke up...
done waiting...

The Node results are what I expected. My understanding is that the tasks created by create_task do not start executing until they are awaited (in the for loop); but how does the for loop advance to begin execution of the second task if the first task has not yet completed?

thanks for your help on this one

1 Answers

My confusion came from not realizing that create_task is used to start coroutines running concurrently. The Python code could be modified so that it gives the Node results by omitting the create_task and instead just awaiting the task:

async def main():

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

Using create_task is similar to using Promise.all on an array of promises in Node.js

Related