Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Giving Up on a Slow Kiosk With Promise.race()

Giving Up on a Slow Kiosk With Promise.race()

Hollins Green’s kiosk takes 0.9 seconds to answer, and Owen’s board shouldn’t wait that long. His Python script gives each kiosk half a second. Its report() wraps each check in asyncio.wait_for() and catches TimeoutError, and Quarry Hill’s failure has its own except clause:

Language: Python
async def report(branch):
    try:
        kiosk = await asyncio.wait_for(
            check_kiosk(branch), timeout=LIMIT
        )
        print(f"{branch}: {kiosk['holds']} holds waiting")
    except TimeoutError:
        print(f"{branch}: no answer in {LIMIT} s")
    except ConnectionError as err:
        print(err)

main() runs every report at once with asyncio.gather() and times the run. For this lesson, the stand-in also prints [kiosk] <branch> answered before it returns. Python’s board takes half a second, and the script ends there:

Language: Text
Quarry Hill kiosk is not answering
[kiosk] Northgate answered
Northgate: 14 holds waiting
[kiosk] Eastfield answered
Eastfield: 9 holds waiting
Hollins Green: no answer in 0.5 s
Checked 4 kiosks in 0.5 s

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

00:00 Hollins Green’s kiosk takes nine tenths of a second, and Owen’s board shouldn’t wait that long. In this lesson, you’ll give up on it in JavaScript, as his Python script does.

00:12 Its report() function wraps each check in wait_for(), with a half-second limit. When time runs out, it raises a TimeoutError; its except clause says so.

00:23 Quarry Hill’s failure has its own clause. For this lesson, the stand-in logs each kiosk’s answer.

00:32 Run it, and Quarry Hill’s kiosk fails first: its error prints. Retrying it is the next lesson’s job. Northgate and Eastfield answer, and their holds print.

00:46 At half a second, wait_for() gives up on Hollins Green.

00:50 The board is done: four kiosks checked in half a second, and the script ends there.

00:58 There’s no wait_for() in JavaScript. The usual build is a race. Promise.race() takes an array of promises, as Promise.all() does.

01:09 Where all() waits for every promise to fulfill, race() settles with the first one to settle, value or error. So you race the kiosk’s check against a timer that throws.

01:23 The timer is a small async function you write yourself. It takes the limit and the branch, and sleeps for the limit. Then it throws an error that names the branch and the milliseconds.

01:37 It never returns, so its promise can only reject. The limit is five hundred, not half, because JavaScript’s timers count in milliseconds, where Python’s count in seconds.

01:51 In report(), the await waits for the race of the kiosk’s check and the timer. If the kiosk wins, the race fulfills with its record, and its holds are logged.

02:03 If the timer wins, the race rejects, and the catch logs the error’s message. Quarry Hill’s error lands in the same catch, so one catch covers both except clauses and anything else.

02:16 At the top level, .map(report) starts every report(), and Promise.all() waits for them. Since each one catches its own error, Quarry Hill can’t stop it this time.

02:29 Run the port, and the board comes out line for line as Python’s. Hollins Green’s line says five hundred milliseconds. Then, checked four kiosks in half a second, where Python’s output ended.

02:43 What does JavaScript do after it? Your turn: pause the video and predict.

02:53 One more line: Hollins Green answered. It comes at nine tenths of a second, and only then does the script end.

03:04 Why the extra line? In Python, calling check_kiosk() only makes a coroutine: wait_for() runs it, and cancels it. Hollins Green’s coroutine stops at its sleep, so the script ends at half a second.

03:19 In JavaScript, calling checkKiosk() already started the check, so the race only gets its promise. It can’t cancel the work, only stop waiting.

03:31 Hollins Green’s check runs on, logs its answer at nine tenths of a second, and the script ends when it’s done.

03:39 The timer runs on too: when Northgate wins, its timeout still throws at half a second, and the settled race ignores it. So read a timeout as stop waiting, not stop working.

03:53 Make sure work that may finish after you’ve given up is safe to finish. Here, the late check only logs. If it also added its holds to a total, they’d still count, after the board said no answer.

04:08 Stopping the work takes a signal, a later topic.

04:13 A relative of race() is Promise.any(): it settles with the first to fulfill and skips rejections, so it would ignore your timer.

04:22 The rule: race the work against a timer that throws, and a lost race gives up on the answer, not the work. Next up, Retrying With try/catch Around await: Quarry Hill gets a second chance.

Become a Member to join the conversation.