12 · Promises, await, Timeouts, and Cancellation
In the previous tutorial, our Jinja page displayed a document’s status:
<strong id="review-status">not_started</strong>Clicking Refresh status caused JavaScript to:
- Send
GET /documents/101/status. - Wait for FastAPI’s response.
- Parse the JSON.
- Replace
pendingwith the current database value.
Today we’ll examine what happens during that wait.
We’ll add:
- A clear loading state
- A five-second timeout
- A Cancel button
- Protection against an old request changing the page after a newer request has begun
The server endpoint remains the same:
Our newly created document now starts as not_started. This lesson still performs a read; the pending Promise discussed below is the browser request’s state, not the document’s review status.
@router.get( "/{document_id}/status", response_model=DocumentStatusRead,)def document_status( response: Response, document: AuthorizedDocument,): response.headers["Cache-Control"] = "no-store"
return documentAuthentication, authorization, the SQLAlchemy session, and the SQLite lookup still occur on every request.
Today’s work lives primarily in the browser:
Click→ JavaScript starts fetch()→ Promise becomes pending→ Browser remains usable→ Response, failure, timeout, or cancellation→ Promise settles→ JavaScript updates the DOMThe updated HTML
Section titled “The updated HTML”We add a Cancel button beside the existing Refresh button:
<p> Review status: <strong id="review-status"> {{ review_document.status }} </strong></p>
<button id="refresh-status" type="button" data-status-url="{{ url_for( 'document_status', document_id=review_document.id ) }}"> Refresh status</button>
<button id="cancel-refresh" type="button" disabled> Cancel</button>
<p id="status-message" role="status"></p>The initial state is intentional:
<button id="refresh-status"> Refresh status</button>The user may start a request.
The Cancel button begins with:
disabledbecause no request exists yet.
Once a request begins, JavaScript will reverse those states:
Refresh status → disabledCancel → enabledWhen the request finishes, fails, times out, or is canceled, JavaScript restores the original state.
The disabled attributes improve the interface, but they provide no security. A user can modify the page or send requests outside the interface.
Authentication and authorization still belong on the server.
The updated JavaScript
Section titled “The updated JavaScript”Here is the complete script:
const refreshButton = document.querySelector("#refresh-status");const cancelButton = document.querySelector("#cancel-refresh");const statusElement = document.querySelector("#review-status");const messageElement = document.querySelector("#status-message");
let activeRequest = null;
refreshButton.addEventListener("click", refreshStatus);cancelButton.addEventListener("click", cancelRefresh);
async function refreshStatus() { activeRequest?.controller.abort();
const controller = new AbortController();
const request = { controller: controller, timedOut: false, };
activeRequest = request; setLoadingState(true);
const timeoutId = window.setTimeout(() => { request.timedOut = true; controller.abort(); }, 5000);
try { const response = await fetch( refreshButton.dataset.statusUrl, { headers: { Accept: "application/json", }, signal: controller.signal, }, );
if (response.status === 401) { throw new Error( "Your session expired. Please sign in again." ); }
if (response.status === 404) { throw new Error( "This document is no longer available." ); }
if (!response.ok) { throw new Error( "Could not refresh the status." ); }
const data = await response.json();
if (activeRequest !== request) { return; }
statusElement.textContent = data.status; messageElement.textContent = "Status updated."; } catch (error) { if (activeRequest !== request) { return; }
if (error.name === "AbortError") { messageElement.textContent = request.timedOut ? "The request took too long." : "Status refresh canceled."; } else if (error instanceof TypeError) { messageElement.textContent = "Connection problem. Please try again."; } else { messageElement.textContent = error.message; } } finally { window.clearTimeout(timeoutId);
if (activeRequest === request) { activeRequest = null; setLoadingState(false); } }}
function cancelRefresh() { activeRequest?.controller.abort();}
function setLoadingState(isLoading) { refreshButton.disabled = isLoading; cancelButton.disabled = !isLoading;
if (isLoading) { messageElement.textContent = "Checking…"; }}There is quite a lot packed into this small file. We’ll follow it in execution order.
Initial script execution
Section titled “Initial script execution”When the browser loads the JavaScript file, these lines run first:
const refreshButton = document.querySelector("#refresh-status");
const cancelButton = document.querySelector("#cancel-refresh");
const statusElement = document.querySelector("#review-status");
const messageElement = document.querySelector("#status-message");Each variable refers to an existing DOM element.
Then we create:
let activeRequest = null;We use let because the value will change.
Initially:
activeRequest === nullNo status request is running.
Later, it will refer to an object containing information about the current request:
{ controller: AbortController, timedOut: false}The script then registers its two event handlers:
refreshButton.addEventListener( "click", refreshStatus,);
cancelButton.addEventListener( "click", cancelRefresh,);The browser stores these relationships:
Refresh click → call refreshStatus()Cancel click → call cancelRefresh()Neither function runs yet.
Calling an async function
Section titled “Calling an async function”When the user clicks Refresh, the browser calls:
refreshStatus()The function was declared as:
async function refreshStatus() {The async keyword has two important effects.
First, it permits await inside the function.
Second, calling an async function always returns a Promise.
Even this function returns a Promise:
async function simpleExample() { return 42;}Calling:
const result = simpleExample();does not place 42 directly into result.
It places a Promise there:
PromiseThat Promise will eventually be fulfilled with:
42An async function’s returned Promise is fulfilled when the function returns normally and rejected when the function throws an uncaught error. MDN’s async-function documentation
Our click event listener does not use the returned Promise directly. The function therefore catches its own expected errors so they do not become unhandled Promise rejections.
What a Promise represents
Section titled “What a Promise represents”A Promise represents the future result of an asynchronous operation.
It can be in one of three states:
| State | Meaning |
|---|---|
pending |
The operation has not completed |
fulfilled |
The operation completed successfully |
rejected |
The operation failed |
A fulfilled or rejected Promise is described as settled.
When we call:
fetch(url)the browser cannot immediately provide the final HTTP response. It must:
- Resolve the destination.
- Open or reuse a network connection.
- Send the request.
- Wait for the server.
- Receive the response.
Instead of freezing JavaScript until all that work completes, fetch() immediately returns a pending Promise. A Promise represents the eventual completion or failure of an asynchronous operation. MDN’s Promise documentation
Conceptually:
const promise = fetch(url);At first:
promise → pendingLater, it becomes either:
fulfilled with a Response objector:
rejected with an errorThe Promise is not the response. It is the mechanism through which JavaScript will later receive the response or failure.
Preparing the request
Section titled “Preparing the request”The first line inside refreshStatus() is:
activeRequest?.controller.abort();The operator:
?.is optional chaining.
It means:
If
activeRequestexists, access its controller and callabort().
If:
activeRequest === nullthe expression quietly does nothing.
This handles a situation where some other code calls refreshStatus() while an older refresh is still pending. The old browser request is canceled before the new one begins.
Our button is disabled during ordinary loading, so the user cannot normally create overlapping requests by clicking repeatedly. This extra protection will become more useful when polling begins automatically.
Next we create:
const controller = new AbortController();An AbortController is a browser object used to signal that an asynchronous operation is no longer wanted. Fetch supports this mechanism through an AbortSignal. MDN’s AbortController documentation
We then create an ordinary JavaScript object:
const request = { controller: controller, timedOut: false,};The shorter equivalent would be:
const request = { controller, timedOut: false,};When a property name and variable name are identical, JavaScript allows this shorthand.
We use the longer form here because it makes the mapping especially visible:
request.controller→ refers to the AbortController object
request.timedOut→ records why an abort occurredThe request object becomes the active one:
activeRequest = request;Entering the loading state
Section titled “Entering the loading state”Next:
setLoadingState(true);calls our ordinary helper function:
function setLoadingState(isLoading) { refreshButton.disabled = isLoading; cancelButton.disabled = !isLoading;
if (isLoading) { messageElement.textContent = "Checking…"; }}For this call:
isLoading === trueTherefore:
refreshButton.disabled = true;disables Refresh.
The next line uses logical negation:
cancelButton.disabled = !isLoading;Since:
!true === falsethe Cancel button becomes enabled.
The browser now shows:
[Refresh status — disabled] [Cancel — enabled]
Checking…This happens before the network response arrives.
A good loading state answers three questions:
Did my click work?Is something happening?Can I safely click again?Without it, a user may assume the application ignored the click and submit the same action repeatedly.
Creating the timeout
Section titled “Creating the timeout”The code now registers a timer:
const timeoutId = window.setTimeout(() => { request.timedOut = true; controller.abort();}, 5000);setTimeout() receives two arguments:
setTimeout(callback, delay)Our callback is:
() => { request.timedOut = true; controller.abort();}This is an arrow function.
The delay is:
5000measured in milliseconds:
5,000 milliseconds = 5 secondsThe browser schedules the callback to become eligible to run after roughly five seconds.
It does not pause here for five seconds. setTimeout() returns immediately and gives us a timer identifier:
timeoutIdWe keep that identifier so we can cancel the timer if the HTTP request finishes first.
Also, five seconds is a minimum scheduling threshold, not an exact appointment. If the browser’s main JavaScript thread is busy at that moment, the callback runs when the thread becomes available. MDN’s setTimeout() documentation
Starting fetch()
Section titled “Starting fetch()”Now we reach:
const response = await fetch( refreshButton.dataset.statusUrl, { headers: { Accept: "application/json", }, signal: controller.signal, },);The new piece is:
signal: controller.signalThe controller owns a signal object. We pass that signal into fetch().
This connects them:
controller.abort() ↓signal becomes aborted ↓fetch stops waiting ↓fetch Promise rejectsThe browser sends:
GET /documents/101/status HTTP/1.1Accept: application/jsonCookie: app_session=...FastAPI authenticates the request, checks authorization, opens a request-scoped SQLAlchemy session, and queries SQLite.
Meanwhile, the Promise returned by fetch() remains pending.
What await actually pauses
Section titled “What await actually pauses”The line contains:
await fetch(...)await pauses the remainder of refreshStatus().
It does not freeze the entire browser.
The browser can still:
- Paint “Checking…” onto the page
- Respond to the Cancel button
- Handle scrolling
- Run timers
- Receive other network responses
- Process events on other page controls
A useful distinction is:
The async function is suspended.The browser is not suspended.The JavaScript statements after await cannot run until the Promise settles. But the browser’s event loop can process other eligible work.
Conceptually, the function is divided into stages:
Stage 1→ Create controller→ Show loading state→ Begin fetch
Pause at await
Stage 2→ Receive Response→ Check status→ Parse body→ Update DOMWhen the fetch Promise settles, the continuation of the function is scheduled to run when the JavaScript thread is available.
This is cooperative concurrency. JavaScript is able to make progress on other events while this function waits, even though the main thread executes one piece of JavaScript at a time.
The successful path
Section titled “The successful path”Suppose FastAPI returns within 100 milliseconds:
HTTP/1.1 200 OKContent-Type: application/json
{"id":101,"status":"completed"}The Promise returned by fetch() becomes fulfilled with a browser Response object.
Execution resumes:
const response = ...The code checks the HTTP status:
if (response.status === 401) { ...}
if (response.status === 404) { ...}
if (!response.ok) { ...}A 404 response fulfills the fetch() Promise because the browser successfully completed the HTTP exchange. Our code converts that unsuccessful HTTP result into a JavaScript error by throwing one.
For a 200, execution reaches:
const data = await response.json();response.json() also returns a Promise because reading and parsing the body may take time.
The function pauses again.
Once the JSON body has been read and parsed, data becomes:
{ id: 101, status: "completed",}Preventing a stale result
Section titled “Preventing a stale result”Before updating the page, we check:
if (activeRequest !== request) { return;}JavaScript compares the two object references.
If they refer to the same object:
activeRequest === requestthis is still the latest request.
If they differ, another request has replaced this one.
Why does that matter?
Imagine two requests:
Request A startsRequest B starts laterRequest B finishes first → status: approvedRequest A finishes later → status: pendingWithout protection, Request A could overwrite the newer result:
approved → pendingThe page would move backward because an older network response happened to arrive later.
This is called a race condition: the visible result depends on timing rather than the intended request order.
Our identity check means:
Only the currently active request may update the page.
If Request A is no longer current, it returns without changing the DOM.
With only our disabled Refresh button, this race is unlikely. The protection becomes valuable once automatic polling, route changes, or multiple page components can initiate requests.
Updating the DOM
Section titled “Updating the DOM”For the current request, JavaScript runs:
statusElement.textContent = data.status;messageElement.textContent = "Status updated.";The database has already provided the authoritative status.
JavaScript now changes only the browser’s representation:
SQLite status ↓SQLAlchemy Document object ↓Pydantic response model ↓JSON response body ↓JavaScript data.status ↓DOM text ↓Pixels on screenThe DOM update does not write anything to SQLite.
It displays the result of the server-side read.
A user cancellation
Section titled “A user cancellation”Now consider a slow request.
The user sees:
Checking…and clicks Cancel.
The browser calls:
cancelRefresh()That function contains:
activeRequest?.controller.abort();The signal passed to fetch() becomes aborted.
The pending fetch Promise rejects, and control moves to:
catch (error) {For an ordinary abort:
error.name === "AbortError"Our request object still contains:
request.timedOut === falseso the page displays:
Status refresh canceled.No unsuccessful status is placed into statusElement. The last known status stays visible.
A timeout
Section titled “A timeout”Suppose five seconds pass without a completed response.
The timeout callback runs:
request.timedOut = true;controller.abort();Again, the fetch Promise rejects with an abort-related error.
This time:
request.timedOut === trueso the page displays:
The request took too long.A timeout is an application decision.
The browser itself may be willing to wait much longer. We have decided that after five seconds, the result is no longer useful enough to keep the interface in a loading state.
Five seconds is only an illustrative value. A quick status lookup might warrant a short timeout. A large upload or AI operation would need a different interaction model rather than a tiny timeout.
Canceling the browser request does not undo server work
Section titled “Canceling the browser request does not undo server work”This distinction matters greatly:
Browser cancellation≠Guaranteed server cancellationWhen JavaScript calls:
controller.abort()the browser stops waiting for the response and attempts to cancel the network operation.
FastAPI may already have received the request.
Python may already be running the dependency.
SQLite may already have completed its query.
For a read-only status request, that extra server work is minor.
For a write request, cancellation does not reliably reverse a transaction that has already committed. If a user submits a document and then cancels the browser request, the server may still create the document.
This means the browser cannot conclude:
I stopped waiting, therefore the operation did not happen.For important writes, applications use tools such as:
- Idempotency keys
- Explicit operation IDs
- Server-side job status
- Safe retry rules
- Database transactions
AbortController controls the client’s interest in the response. It is not a distributed rollback mechanism.
Other errors
Section titled “Other errors”The catch block handles three categories:
if (error.name === "AbortError") {This is cancellation or our timeout.
else if (error instanceof TypeError) {fetch() commonly rejects with a TypeError for problems such as a network failure, DNS failure, or blocked request.
We display:
Connection problem. Please try again.The final branch handles errors that our own code threw:
else { messageElement.textContent = error.message;}For example:
throw new Error( "Your session expired. Please sign in again.");creates an Error object whose message property contains that text.
The throw immediately stops normal execution inside the try block. JavaScript looks for the nearest matching catch.
This parallels Python:
raise HTTPException(...)Both languages use exceptions to leave the normal success path, although the particular objects and surrounding frameworks differ.
Why finally matters
Section titled “Why finally matters”Whether the request succeeds or fails, JavaScript eventually enters:
finally { window.clearTimeout(timeoutId);
if (activeRequest === request) { activeRequest = null; setLoadingState(false); }}First:
window.clearTimeout(timeoutId);removes the five-second timer if it has not fired.
Without this line, a successful request could finish in 100 milliseconds, update the page, and then have its old timer fire several seconds later.
The timer would abort an already completed fetch, which might not visibly hurt anything, but leaving obsolete callbacks around makes the program harder to reason about.
Then we again confirm this is the current request:
if (activeRequest === request) {If it is, we clear it:
activeRequest = null;and leave the loading state:
setLoadingState(false);For that call:
isLoading === falseTherefore:
refreshButton.disabled = false;cancelButton.disabled = true;The interface returns to:
[Refresh status — enabled] [Cancel — disabled]finally is the natural home for cleanup that must happen after either success or failure.
The same logic without async and await
Section titled “The same logic without async and await”The core request could be written with explicit Promise methods:
fetch(url) .then((response) => { if (!response.ok) { throw new Error("Status request failed."); }
return response.json(); }) .then((data) => { statusElement.textContent = data.status; }) .catch((error) => { messageElement.textContent = error.message; }) .finally(() => { setLoadingState(false); });The equivalent async form is:
try { const response = await fetch(url);
if (!response.ok) { throw new Error("Status request failed."); }
const data = await response.json();
statusElement.textContent = data.status;} catch (error) { messageElement.textContent = error.message;} finally { setLoadingState(false);}These are two syntaxes for coordinating Promise-based operations.
async and await do not change HTTP or make the request synchronous. They make asynchronous control flow resemble ordinary sequential code.
The complete execution trace
Section titled “The complete execution trace”For a successful refresh:
- The user clicks Refresh.
- The browser calls
refreshStatus(). - JavaScript creates an
AbortController. - JavaScript disables Refresh and enables Cancel.
- JavaScript schedules the timeout callback.
fetch()creates a pending Promise and sends the request.awaitsuspends the remainder ofrefreshStatus().- The browser remains responsive.
- FastAPI receives the request and resolves its dependencies.
- SQLAlchemy queries SQLite.
- FastAPI serializes the authorized document status.
- The HTTP response reaches the browser.
- The fetch Promise becomes fulfilled.
- The JavaScript function resumes.
response.json()reads and parses the response body.- JavaScript confirms this is still the active request.
- JavaScript updates the DOM.
finallyclears the timeout.- JavaScript restores the buttons.
For a timeout:
- The request begins normally.
- Five seconds pass.
- The timer marks the request as timed out.
- The controller aborts the browser’s fetch.
- The fetch Promise becomes rejected.
catchdisplays the timeout message.finallyclears state and restores the buttons.- The server may still finish work it already began.
The key idea is that await suspends one function while the browser continues handling other events. The Promise records the future outcome, and the interface represents the current state of that operation.
The next installment will use this foundation to replace manual Refresh clicks with controlled polling: the browser will periodically ask FastAPI whether a document review has moved from pending to processing, completed, or failed.
If you would like to pause here and understand the event loops behind these examples, lesson 17 follows that coordination on both the browser and Python sides. You can also continue to polling and return to that explanation later.