Stopping a Poll With AbortController

At the end of a shift, the operator presses stop, and any station poll still running should end. Promise.race() can’t do this. When a timeout wins the race, your code stops waiting, but the losing poll keeps going:

Language: JavaScript
import { setTimeout as sleep } from "node:timers/promises";

async function pollStation(name) {
  await sleep(200);
  console.log(name, "poll finished");
}

const deadline = sleep(100, "timed out");
console.log(await Promise.race([pollStation("Ridge"), deadline]));

The race reports the timeout, and the poll finishes anyway:

Language: Program Output
timed out
Ridge poll finished

In this lesson, you’ll find out what JavaScript’s stop button actually stops and make it stop the poll.

Press Stop on a Running Poll

In Python, a running poll is an asyncio task, and the task is the handle you cancel. Here, asyncio.sleep() stands in for each network read and returns the sample:

Language: Python
import asyncio

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

async def main():
    poll = asyncio.create_task(poll_station("Ridge", [8, 12, 10]))
    await asyncio.sleep(0.15)
    print("operator pressed stop")
    poll.cancel("operator stopped poll")
    try:
        await poll
    except asyncio.CancelledError as error:
        print("cancelled:", error)

asyncio.run(main())

The poll never reads its second sample:

Language: Program Output
Ridge reading 8
operator pressed stop
cancelled: operator stopped poll

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.