3 ms·
The example with parent() awaiting a child() is showing.. nothing? Maybe I am missing some subtlety but here is a JS example that is equivalent: async functi
by IgorPartola 11mo ago
The example with parent() awaiting a child() is showing.. nothing? Maybe I am missing some subtlety but here is a JS example that is equivalent:
async function sleep(t) {
return new Promise((resolve) => {
setTimeout (() => resolve(), t)
})
}
async function child() {
console.log("child start")
await sleep(500)
console.log("child end")
}
async function parent () {
console.log("parent start")
await child()
console.log("parent end")
}
parent()
It will print:
parent start
child start
child end
parent end
Just like the Python version. This article is confusing the fact that JS has a lot more code that returns a promise than Python and thinks it means the behavior is different. It isn’t.
You can roll your own event loop without asyncio by accumulating coroutines in Python and awaiting them in whatever order you want. There is no built-in event loop, however. You can do the same in JavaScript but there you do have a fairly complex event loop (see microtasks) as in there is no running environment without it and if you want a secondary one you have to roll it yourself.
create_task() simply registers a coroutine with the event loop and returns a “future” which basically says “once the main event loop is done awaiting your coroutine this is the ticket to get the result/exception”. That’s the whole magic of an event loop. It is the difference between dropping off a shirt at a dry cleaner and waiting there for them to be done with it (no you aren’t doing the work but you are also not doing anything else), and dropping it off then leaving to get lunch then coming back to wait until the cleaner is done with your pickup ticket in hand (concurrency).
But fundamentally awaiting an async function that doesn’t actually do anything async won’t give you parallelism in a single-threaded environment. More at 11.