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

Reserving a Slot Before You Await

Reserving a Slot Before You Await

In this lesson, you port an asyncio reservation for a station poll and make it safe. Ridge’s satellite uplink has one extra polling slot this shift, and two callers ask for it at the same moment: the dashboard’s auto-refresh and the operator’s Refresh button. Can both of them get it?

In the Python script, stock counts the slots left: one. poll() stands in for the station poll, and the cache answers it at once. reserve() returns "sold out" when the stock is zero. Otherwise, it awaits the poll, takes one off the stock, and returns "reserved":

Language: Python
import asyncio

stock = 1

async def poll(): ...  # the cache answers at once

async def reserve():
    global stock
    if stock == 0:
        return "sold out"
    await poll()
    stock -= 1
    return "reserved"

async def main():
    results = await asyncio.gather(reserve(), reserve())
    print(results, stock)

asyncio.run(main())

asyncio.gather() runs two reserve() calls together, and the script prints ['reserved', 'sold out'] 0.

In the JavaScript port, stock is a let, a variable you can reassign. There’s no global line: assigning to stock inside a function updates the outer let. poll() is an async function with an empty body, so its promise is fulfilled at once.

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 port an asyncio reservation for a station poll and make it safe. Ridge’s uplink has one extra polling slot this shift, and two callers ask for it at the same moment.

00:12 Can both get it? In the Python script, stock counts the slots left: one. poll() is the station poll, and the cache answers it at once.

00:23 reserve() returns sold out at zero. Otherwise, it awaits the poll, takes one off, and returns reserved. asyncio.gather() runs both calls, and the script prints reserved, sold out, and a stock of zero.

00:39 In the JavaScript port, stock is a let, a variable you can reassign. There’s no global line: assigning to stock inside a function updates the outer let. poll() is an async function with an empty body, so its promise is fulfilled at once.

00:55 reserve() keeps the same order: check, await, subtract, return. A one-statement if can sit on one line, without braces. Promise.all(), JavaScript’s asyncio.gather(), waits for both calls.

01:10 A module can await at top level, so there’s no main() or asyncio.run(). What does the last line print? Your turn: pause the video and predict.

01:25 Both calls return reserved, and the stock is minus one.

01:31 Why did the second call get through? Each reserve() call runs at once, up to its first await. And as the refresh routine’s trace showed, a JavaScript await always pauses, even on a fulfilled promise.

01:45 So the first call checks, finds one, and pauses at its await. The second call starts, finds one too, and pauses as well. Then the first call resumes and subtracts: zero.

01:58 The second call resumes and subtracts again: minus one. The run-to-completion that keeps a timer from interrupting your code ends at every await.

02:10 What a function checked before an await can change before it resumes.

02:16 So why did Python print sold out? As the refresh routine showed, asyncio’s await on a coroutine that never pauses doesn’t give up the loop, so the first call checked and subtracted in one go.

02:30 Swap the poll for a wait that really pauses, asyncio.sleep(0), and Python prints reserved twice and minus one.

02:39 The gap was in Python all along; the cached poll hid it. JavaScript opens it at every await. And no delay closes it: from zero to three hundred milliseconds, the port oversells every time.

02:56 The fix is to check and take the slot in one piece, with no await between them. In both files, the subtraction moves above the await. The scripts print reserved, sold out, and a stock of zero.

03:10 Now the first call checks, subtracts, and only then pauses. When the second call checks, the stock is zero, so it returns sold out without polling. Checking again after the await also works, but by then both calls have polled the uplink, which had room for one.

03:29 A poll can fail. If the Ridge link is down, the slot shouldn’t stay used. So reserve() wraps the await in try and catch.

03:38 On failure, catch adds the slot back with stock += 1, then throws the same error on, like a bare raise in Python. JavaScript has no bare form, so you name the error again.

03:51 A failed poll leaves the stock at one, so a caller turned away meanwhile can ask again. A successful poll keeps the slot, so the stock stays at zero.

04:04 So when an async function checks shared state and then changes it, do both before the first await, and undo the change only if the awaited work fails. It’s the same fix in asyncio; JavaScript never lets an await skip the pause.

04:19 Next up is the exercise Release a Station Poll Permit. There, a station poll’s permit comes back whether the poll succeeds or fails, and an overlapping call is rejected before its poll starts.

04:32 You’ll test it with promises you control, not timings.

Become a Member to join the conversation.