Web Development Pro | Lesson 032 | Asynchronous Work and Promises
Web Development Pro · Lesson 32 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 31 first. This lesson builds on event loop ordering and async/await. By the end, you can explain asynchronous completion and write awaited operations with error handling. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Plan for work that finishes later
A page may need data that is not immediately available. JavaScript must allow the interface to continue while that work proceeds. A Promise represents a future completion or failure. It can be pending, fulfilled with a value, or rejected with a reason. A promise is not the eventual data itself, so reading a property from the promise does not read a downloaded record.
This lesson uses a short local timer to make completion order visible without contacting a server. The timer simulates delay; it does not guarantee execution at an exact millisecond. Browser scheduling and other work can delay the callback beyond the requested minimum.
Create a small asynchronous helper
The wait function returns a promise resolved by setTimeout. ReadDemo waits for that promise, then either returns a fictional value or throws an error. The default parameter false means a caller that omits the argument uses the ordinary success path. Both paths are supplied so tests can cover rejection deliberately.
File async.mjs:
export function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
export async function readDemo(shouldFail = false) {
await wait(10);
if (shouldFail) throw new Error('Demonstration source unavailable.');
return 'Bicycle basics is ready.';
}
An async function always returns a promise. Returning a string fulfills that promise with the string. Throwing rejects it. Await pauses that async function's continuation until the awaited value settles; it does not freeze the entire browser or turn asynchronous work into a blocking network call.
Show loading, success, and failure
The page should describe the state it is actually in. Before completion, show a loading message. After fulfillment, show the returned data. After rejection, show a useful recovery message rather than leaving “Loading” on screen indefinitely. The complete page provides a short status paragraph and loads the entry as a module.
File app.mjs:
import { readDemo } from './async.mjs';
const status = document.querySelector('#async-status');
if (!status) throw new Error('Async status is missing.');
export async function showDemo(shouldFail = false) {
status.textContent = 'Loading the local demonstration…';
try {
const message = await readDemo(shouldFail);
status.textContent = message;
} catch (error) {
status.textContent = 'The demo could not load. Try the exercise again.';
console.error(error.message);
}
}
export const ready = showDemo();
The exported ready promise is useful to the supplied tests, which await the initial demonstration before making assertions. It is not a hidden helper or an external service. ShowDemo catches the expected failure and updates the interface, so callers do not receive an unhandled rejection for that deliberately handled case.
Follow the order carefully
When showDemo is called, it immediately writes the loading message and begins the awaited work. Control returns to its caller with a promise before the final sentence is available. After the timer resolves, the continuation updates the status. Code placed immediately after showDemo() cannot assume the data has already appeared unless it awaits the returned promise.
Promise callbacks run through the microtask mechanism after the current synchronous work completes. A timeout callback is scheduled as a later task. You do not need to memorize every event-loop detail yet, but you should know that even an already fulfilled promise's then callback does not run inline as an ordinary immediate function call.
Avoid using a fixed delay as a substitute for waiting on the operation you actually need. “Wait two seconds, then read results” is unreliable if the operation takes longer or shorter. Await the real promise or another explicit completion signal. Timing guesses create flaky interfaces and tests.
Catch failures where they can be handled
A try/catch around an awaited promise can catch its rejection. A try/catch that starts an asynchronous operation without awaiting or returning it will not automatically catch a later rejection. The error belongs to the asynchronous chain, so keep that chain connected.
Catching an error should lead to a useful outcome: a recovery state, a deliberate fallback, or a rethrow to a layer that can handle it. Silently swallowing every error makes a broken page look inexplicably empty. Conversely, exposing raw stack traces to visitors is rarely helpful and can reveal implementation details. Separate developer diagnostics from user-facing feedback.
Use finally for cleanup that should happen after either success or failure, such as removing a loading flag. It does not replace catch when a rejected result needs a message. Be careful that cleanup itself does not throw and hide the original failure. Later lessons use explicit state updates to keep these transitions easy to inspect.
Test completion instead of guessing timing
The tests await readDemo and the exported ready promise rather than sleeping an arbitrary extra amount. They check the success value, the intentional rejection, and the status after showDemo(true). A separate ordering assertion shows synchronous logging before a promise continuation.
These are real Node promise and timer executions. The DOM status assignment uses the limited double, so live announcements and visible loading presentation remain browser checks. The small timer is only a teaching fixture; its duration is not a performance claim about a real network.
Worked practice
Worked exercise 1: Read the eventual value
Task: const result = readDemo() is followed by result.toUpperCase(). Worked answer: await readDemo() inside an async function, then use the fulfilled string. Without awaiting, result is a promise and does not represent the final message string.
Worked exercise 2: Catch a rejection
Task: A try block calls readDemo(true) without await, and catch does not handle the later failure. Worked answer: await the promise within the try block, or return a properly handled promise chain. The asynchronous failure must remain connected to the handling code.
Worked exercise 3: Remove a timing guess
Task: A test waits exactly ten milliseconds and then checks the message. Worked answer: await the operation's returned promise. A timer's requested delay does not guarantee that all subsequent asynchronous work completed by that wall-clock moment.
Knowledge check
Question 1
What does an async function return? A) Always its raw final value immediately. B) A promise. C) The value returned by the first await directly. D) A timer identifier by definition.
Check question 1: answer and explanation
Answer: B. Its eventual returned value fulfills the promise, and thrown errors reject it.
Question 2
What does await pause? A) The current async continuation. B) The whole event loop until the promise settles. C) Every other async function that is currently running. D) The timer and network work needed to settle the promise.
Check question 2: answer and explanation
Answer: A. Other work can continue while the awaited operation is pending.
Question 3
Why is a fixed sleep a weak completion test? A) A fulfilled promise cannot be observed with await. B) A timer guarantees the operation finished at exactly its requested delay. C) Scheduling and operation duration can vary. D) The promise result is available as soon as the timer is scheduled.
Check question 3: answer and explanation
Answer: C. Waiting on the actual completion contract is more reliable than a guessed delay.
Question 4
Which try/catch can handle a promise rejection directly? A) One that ignores the returned promise. B) One that only logs before starting it. C) One outside an unrelated callback. D) One that awaits the promise inside try.
Check question 4: answer and explanation
Answer: D. Await connects the rejection to that control flow.
Question 5
What should a handled failure produce in this interface? A) A clear recovery state instead of endless loading. B) A successful empty result indistinguishable from a load error. C) An unchanged spinner forever. D) A resolved status inferred solely from elapsed time.
Check question 5: answer and explanation
Answer: A. Feedback should reflect the actual outcome and allow the person to recover.