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

Combining a Deadline and an Operator Stop

Combining a Deadline and an Operator Stop

In this lesson, you give a station poll a deadline as well as a stop button, and make one signal carry both. A hung poll shouldn’t hold the dashboard forever, so Ridge gets 250 milliseconds; each reading takes 100.

In Python, asyncio.timeout() puts the deadline around the await. The poll closes its station link in a finally block; the print() stands in for a real connection:

Language: Python
import asyncio

async def poll_station(name, samples):
    try:
        for sample in samples:
            reading = await asyncio.sleep(0.1, result=sample)
            print(name, "reading", reading)
        print(name, "poll finished")
    finally:
        print(name, "link closed")

async def main():
    try:
        async with asyncio.timeout(0.25):
            await poll_station("Ridge", [8, 12, 10])
    except TimeoutError as error:
        print("name:", type(error).__name__)

asyncio.run(main())

The log shows two readings, link closed, then the TimeoutError that main() caught:

Language: Program Output
Ridge reading 8
Ridge reading 12
Ridge link closed
name: TimeoutError

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 In this lesson, you’ll give a station poll a deadline as well as a stop button, and make one signal carry both. A hung poll shouldn’t hold the dashboard forever, so Ridge gets 250 milliseconds; each reading takes 100.

00:15 In Python, asyncio.timeout() puts the deadline around the await. The poll closes its station link in a finally block; the print stands in for a real connection.

00:28 The log shows two readings, link closed, then the TimeoutError that main() caught.

00:34 On the right is the previous lesson’s poll, now in try and finally, minus its empty-station check: Ridge has samples.

00:43 JavaScript has no timeout block; the deadline is a signal: AbortSignal.timeout(250) returns a signal that aborts itself after 250 milliseconds.

00:55 The poll passes it to sleep(), like the controller’s signal. Watch out: a Promise.race() against a timer is like asyncio.wait() with a timeout: only your waiting stops, while the poll and timer run on; the signal stops the read.

01:12 try and finally carry over unchanged. The catch block logs the error’s name, then its cause in a template literal, a backtick string that fills in ${} like an f-string.

01:23 Python caught a TimeoutError, so what name does the JavaScript catch block log? Your turn: pause the video and predict.

01:37 It’s AbortError, not TimeoutError, and the next line shows a TimeoutError as the error’s cause.

01:46 It’s the same AbortError the operator’s stop produced last lesson: sleep() reports every abort the same way and copies the signal’s reason to the error’s cause.

01:56 A timeout signal’s reason is a TimeoutError: The operation was aborted due to timeout.

02:02 Python’s asyncio.sleep() can’t tell either: inside the poll, the deadline arrives as a CancelledError, and asyncio.timeout() swaps it for a TimeoutError on the way out.

02:14 JavaScript has no block to make that swap, so sleep() rejects with AbortError, the TimeoutError as its cause.

02:22 That name isn’t the same for every API: fetch(), the built-in function for HTTP requests, rejects with the reason itself, a TimeoutError.

02:33 So check what each API rejects with, and find the deadline in the reason.

02:39 The operator’s stop button still has to work. In Python, the operator’s cancel() and asyncio.timeout() both cancel the task; the caller tells them apart by type, since asyncio.timeout() turns its own cancel into a TimeoutError.

02:55 The analogy stops at reach: a cancelled task stops at whatever await it’s on, while a signal reaches only the calls you hand it to. In JavaScript, the poll takes one signal, so the caller combines two.

03:10 AbortSignal.any() takes an array of signals and returns one that aborts as soon as any of them does, with that signal’s reason. The poll moves to its own module, poll.mjs, with export in front, since JavaScript imports only what a module exports, unlike Python.

03:29 As before, a timer stands in for the operator, pressing stop after 150 milliseconds. AbortSignal.any() gets an array of the two: the operator’s controller.signal and a fresh 250-millisecond timeout.

03:44 The log shows one reading, the stop, link closed, and an AbortError again. This time, the cause is the operator’s reason.

03:55 If the operator waits past 250 milliseconds, the deadline fires first, and the catch block logs deadline.mjs’s two lines. One catch block, one error name, and the cause says which one ended the poll.

04:10 Either way, finally closed the link before the catch block ran, as in Python, and poll finished never printed: cleanup belongs in finally.

04:21 So to give work a deadline and a stop button, combine both signals with AbortSignal.any(), pass the one signal into every operation that accepts it, and clean up in finally.

04:33 Unlike except TimeoutError, a catch block takes every error: if it’s the stop or the deadline, as stoppedBy() checked earlier, read the reason to see which fired; throw anything else on.

04:45 Next up is the exercise Cancel the End-of-Shift Poll. There, you’ll write the dashboard’s poll helper so it takes its caller’s stop signal.

Become a Member to join the conversation.