Skip to content

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:

  1. Send GET /documents/101/status.
  2. Wait for FastAPI’s response.
  3. Parse the JSON.
  4. Replace pending with 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 document

Authentication, 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 DOM

We add a Cancel button beside the existing Refresh button:

app/templates/documents/detail.html
<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:

disabled

because no request exists yet.

Once a request begins, JavaScript will reverse those states:

Refresh status → disabled
Cancel → enabled

When 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.


Here is the complete script:

app/static/document-status.js
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.


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 === null

No 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.


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:

Promise

That Promise will eventually be fulfilled with:

42

An 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.


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:

  1. Resolve the destination.
  2. Open or reuse a network connection.
  3. Send the request.
  4. Wait for the server.
  5. 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 → pending

Later, it becomes either:

fulfilled with a Response object

or:

rejected with an error

The Promise is not the response. It is the mechanism through which JavaScript will later receive the response or failure.


The first line inside refreshStatus() is:

activeRequest?.controller.abort();

The operator:

?.

is optional chaining.

It means:

If activeRequest exists, access its controller and call abort().

If:

activeRequest === null

the 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 occurred

The request object becomes the active one:

activeRequest = request;

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 === true

Therefore:

refreshButton.disabled = true;

disables Refresh.

The next line uses logical negation:

cancelButton.disabled = !isLoading;

Since:

!true === false

the 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.


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:

5000

measured in milliseconds:

5,000 milliseconds = 5 seconds

The 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:

timeoutId

We 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


Now we reach:

const response = await fetch(
refreshButton.dataset.statusUrl,
{
headers: {
Accept: "application/json",
},
signal: controller.signal,
},
);

The new piece is:

signal: controller.signal

The controller owns a signal object. We pass that signal into fetch().

This connects them:

controller.abort()
↓
signal becomes aborted
↓
fetch stops waiting
↓
fetch Promise rejects

The browser sends:

GET /documents/101/status HTTP/1.1
Accept: application/json
Cookie: 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.


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 DOM

When 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.


Suppose FastAPI returns within 100 milliseconds:

HTTP/1.1 200 OK
Content-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",
}

Before updating the page, we check:

if (activeRequest !== request) {
return;
}

JavaScript compares the two object references.

If they refer to the same object:

activeRequest === request

this is still the latest request.

If they differ, another request has replaced this one.

Why does that matter?

Imagine two requests:

Request A starts
Request B starts later
Request B finishes first → status: approved
Request A finishes later → status: pending

Without protection, Request A could overwrite the newer result:

approved → pending

The 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.


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 screen

The DOM update does not write anything to SQLite.

It displays the result of the server-side read.


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 === false

so the page displays:

Status refresh canceled.

No unsuccessful status is placed into statusElement. The last known status stays visible.


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 === true

so 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 cancellation

When 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.


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.


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 === false

Therefore:

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 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.


For a successful refresh:

  1. The user clicks Refresh.
  2. The browser calls refreshStatus().
  3. JavaScript creates an AbortController.
  4. JavaScript disables Refresh and enables Cancel.
  5. JavaScript schedules the timeout callback.
  6. fetch() creates a pending Promise and sends the request.
  7. await suspends the remainder of refreshStatus().
  8. The browser remains responsive.
  9. FastAPI receives the request and resolves its dependencies.
  10. SQLAlchemy queries SQLite.
  11. FastAPI serializes the authorized document status.
  12. The HTTP response reaches the browser.
  13. The fetch Promise becomes fulfilled.
  14. The JavaScript function resumes.
  15. response.json() reads and parses the response body.
  16. JavaScript confirms this is still the active request.
  17. JavaScript updates the DOM.
  18. finally clears the timeout.
  19. JavaScript restores the buttons.

For a timeout:

  1. The request begins normally.
  2. Five seconds pass.
  3. The timer marks the request as timed out.
  4. The controller aborts the browser’s fetch.
  5. The fetch Promise becomes rejected.
  6. catch displays the timeout message.
  7. finally clears state and restores the buttons.
  8. 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.