Awaiting Each Kiosk in Turn

So far, your port asks a single kiosk, Northgate, and you’ve seen that an async call hands back a promise, and awaiting it gives you its result. Owen’s morning board needs a total of every branch’s holds and a note of how long the check took, so he can tell when a kiosk is dragging.

In Python, collecting the kiosk records takes one line inside main(). The natural JavaScript port of that line runs without an error and gets the total and the timing wrong. In this lesson, you’ll see why and write the loop a JavaScript developer would use to ask the kiosks one after another.

Port the Comprehension to .map()

Owen’s Python script collects records from the three kiosks with an async comprehension, sums their holds, and times the whole run with time.perf_counter():

Language: Python
import asyncio
import time

KIOSKS = {
    "Northgate": {"delay": 0.12, "holds": 14},
    "Eastfield": {"delay": 0.25, "holds": 9},
    "Hollins Green": {"delay": 0.9, "holds": 6},
}

async def check_kiosk(branch):
    kiosk = KIOSKS[branch]
    await asyncio.sleep(kiosk["delay"])
    return {"branch": branch, "holds": kiosk["holds"]}

async def main():
    start = time.perf_counter()
    kiosks = [await check_kiosk(branch) for branch 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")

if __name__ == "__main__":
    asyncio.run(main())

Python prints Total: 29 holds waiting and Checked 3 kiosks in 1.3 s. That’s 0.12 plus 0.25 plus 0.9 seconds, because the comprehension waits for each kiosk before it asks the next. Quarry Hill’s new kiosk isn’t on the list yet.

In JavaScript, a list comprehension becomes .map(), which calls an arrow function for each item and collects what the arrow returns into a new array. Object.keys(KIOSKS) gives it the branch names, as looping over the dict does in Python. The sum becomes .reduce(), which starts from 0 and adds each kiosk’s holds.

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.