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