Async JavaScript for Pythonistas (Summary)

Ashdown Libraries’ holds check now runs in JavaScript. On the first morning, branch-status.js prints the same seven lines as Owen’s branch_status.py, from Northgate: 14 holds waiting to Checked 4 kiosks in 0.5 s. Hollins Green shows no answer, Quarry Hill’s three holds arrive on its second try, and on the second morning, the script prints Yesterday: 26.

Before you write your next async script, sort the asyncio habits you brought with you into the ones that carry across to JavaScript and the ones to drop.

Carry Each asyncio Habit Across

Here’s each asyncio habit next to the JavaScript you now write in its place:

asyncio JavaScript
async def run by asyncio.run(main()) async function, awaited at the top level of a module
await asyncio.sleep(0.12) await sleep(120), with setTimeout imported as sleep from node:timers/promises
a coroutine object that waits to be awaited a promise, whose work starts when you call the function
[await check_kiosk(b) for b in KIOSKS] for...of, pushing each awaited result onto an array
await asyncio.gather(*coros) await Promise.all(array)
gather(..., return_exceptions=True) Promise.allSettled(), branching on result.status
asyncio.wait_for(coro, timeout=LIMIT) Promise.race() against a timeout() helper
try/except around return await try/catch around return await, the same rule
except ConnectionError catch (err), checking a field such as err.code and rethrowing other errors
create_task() awaited later the call with .catch() attached where it starts

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.