Waiting for Every Kiosk With Promise.all()
Both versions, Python and your for...of port, ask the kiosks one after another, so both take
1.3 seconds. The three kiosks don’t depend on each other, so in Python you’d ask them all at once.
Inside main(), asyncio.gather() takes a check for each branch and waits for all of them:
async def main():
start = time.perf_counter()
kiosks = await asyncio.gather(
*(check_kiosk(b) for b in KIOSKS)
)
total = sum(kiosk["holds"] for kiosk in kiosks)
print(f"Total: {total} holds waiting")
elapsed = time.perf_counter() - start
print(f"Checked {len(kiosks)} kiosks in {elapsed:.1f} s")
It prints Total: 29 holds waiting and Checked 3 kiosks in 0.9 s.
In JavaScript, gather()’s job belongs to Promise.all(). The .map() call gives back an
array of promises, one for each kiosk check. That is what Promise.all() needs.
JavaScript’s spread, three dots, unpacks an array into separate arguments, as the star does in a
Python call. With the same stand-in as before, the line-by-line port is: