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

Handling a Promise You Await Later

Handling a Promise You Await Later

Owen’s board also shows yesterday’s total, from a small history file the script writes each morning. His Python script starts reading it before asking the kiosks, with asyncio.create_task(), so the file loads while the kiosks answer. The read itself runs in asyncio.to_thread(), because reading a file would block. After the board, the script awaits the task inside try, and a missing file means there’s no history yet:

Language: Python
HISTORY = Path("history.json")

async def load_history():
    text = await asyncio.to_thread(
        HISTORY.read_text, encoding="utf-8"
    )
    return json.loads(text)["total"]

async def main():
    history = asyncio.create_task(load_history())
    # ... await gather() on the kiosks, then print the board's four lines
    try:
        yesterday = await history
    except FileNotFoundError:
        yesterday = "no history yet"
    print(f"Total: {total} holds waiting (yesterday: {yesterday})")

On the first morning there’s no history.json yet. The read fails, the except clause catches the error at the await, and the board ends with yesterday’s part reading “no history yet”:

Language: Text
Northgate: 14 holds waiting
Eastfield: 9 holds waiting
Hollins Green: 6 holds waiting
Quarry Hill: no answer (Quarry Hill kiosk is not answering)
Total: 29 holds waiting (yesterday: no history yet)

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 Owen’s board also shows yesterday’s total, from a history file the script writes each morning. His Python script starts the read with create_task() before asking the kiosks, and awaits it after the board, inside a try.

00:15 A missing file means no history yet. One line of this has no exact twin in JavaScript: in this lesson, you’ll port it and see where it bites.

00:27 On the first morning, there’s no history file yet. Run it: the board prints its four branch lines.

00:36 Then the total, with yesterday’s part reading no history yet. The read failed, and the except clause caught it at the await.

00:46 The port keeps the file name and makes loadHistory() an async function. Python’s to_thread() reads in a worker thread; in JavaScript, readFile() from fs/promises is async already, so there’s no thread to ask for.

01:02 JSON.parse() turns the text into an object, as json.loads() does. Calling an async function starts its work, as you saw with the kiosks.

01:13 So create_task() has no twin: a plain call starts the read, and history holds its promise.

01:22 The kiosks and the board stay as you ported them, with Promise.allSettled(). After the board, a try waits for the read, as Python’s does.

01:32 yesterday is declared before the try: a let inside the braces wouldn’t be seen after them. JavaScript has no file-not-found error, so the catch reads the error’s code.

01:44 A missing file has the code ENOENT; any other error is thrown again. Otherwise, yesterday reads no history yet, and the total line prints it.

01:59 It’s the first morning again: no history file. Python printed the board and no history yet. What does the port print? Your turn: pause the video and predict.

02:16 Nothing at all. Within milliseconds, Node stops with the missing file’s error, and exit code one. The board never prints, and the catch never runs.

02:31 The await is inside the try, as the retry lesson had it, and still the catch never ran. The read fails a few milliseconds in, while the kiosks are still answering.

02:43 Nothing is listening to its promise yet: the await is nearly a second away. The promise keeps its error, but Node doesn’t wait for the await.

02:54 It treats a rejection nobody handles like an uncaught exception, and ends the program. Python’s task keeps its error too, and waits quietly until something awaits it.

03:06 The fix: attach the handler where the work starts. The .catch() method takes a callback for the error, and gives back a new promise. Now, when the read fails, the handler’s already there.

03:21 Its callback turns ENOENT into no history yet. Anything else is thrown again: the new promise rejects, nobody’s listening, and the script stops before the board.

03:33 history no longer rejects on a missing file, so the try block can go, and the await moves into the total line. Run it, and the board matches Python’s, total and all.

03:46 Watch out for a call you never await at all, such as a save into a logs folder that isn’t there, with writeFile() and no await.

03:54 The port prints board saved, then stops the same way, with exit code one. Python’s create_task() of the same write, failing while the script runs on, only logs: Task exception was never retrieved.

04:09 And it carries on, without the save.

04:13 The rule: every promise needs a handler by the time it can fail. Await it straight away, or catch it on the line that starts it. Next up is the exercise Retry the Returns Machines: Quarry Hill’s machine gets asked again, and the board ends with the day’s notices.

Become a Member to join the conversation.