When you build a TypeScript app that talks to an HTTP API, you almost always use fetch, the built-in function in browsers and Node for making network requests. fetch returns a promise, an object that represents a value that will be available now, later, or never, depending on when the server responds. Async/await, the syntax added to JavaScript in ES2017, lets you write code that waits on that promise as if it were a normal synchronous call, reading top to bottom instead of nesting callbacks.
Mark your function async and await the fetch call to get the response. Then check response.ok before parsing the body, parse the JSON, type the result with a TypeScript interface, and wrap the whole thing in try/catch. The response.ok check goes first because fetch resolves its promise even when the server returns an HTTP error status; that check turns an HTTP error into an error you can catch.
By the end you will be able to write a typed fetch function that returns a promise with the data you expect, handles failures without crashing, and cancels in-flight requests when a component no longer needs them.
How async/await reads the promise flow
An async function always returns a promise. If the function body returns a value, that value becomes the resolved value of the promise; if the body throws, the function returns a rejected promise instead. You can only use the await keyword inside an async function. It pauses that function until the promise settles, then hands you the resolved value.
fetch returns a promise that resolves to a Response object. The simplest correct call needs two awaits: one for the network exchange, and one for reading the body.
async function fetchUser() {
try {
const response = await fetch("https://api.example.com/user");
const user = await response.json();
console.log(user);
} catch (error) {
console.error("Request failed:", error);
}
}
The first await waits for the server to respond. The second await waits for response.json to finish reading and parsing the body. Because each await pauses the function, the three lines read like ordinary synchronous code, which is the main reason async/await improves readability over promise chaining.
A subtlety: fetch rejects its promise only when the request fails at the network level, such as a dropped connection or a DNS failure. An HTTP error status still resolves with a Response object. That is why every robust example checks response.ok before doing anything with the body.
Typing the response with interfaces
TypeScript gives response.json the return type Promise. The compiler does not know what the server will send, so it types the parsed body as any and you get no safety. You provide the shape.
A TypeScript interface declares the properties an object has and their types. It exists only during type checking; the compiler erases it and generates no JavaScript, so it costs nothing at runtime. The compiler then catches mismatches at compile time rather than when your app runs, as explained in the TypeScript interface guide.
interface User {
id: number;
name: string;
email: string;
}
async function fetchUser(id: number): Promise<User> {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json() as User;
}
The as User cast tells TypeScript what the body contains. It does not verify what the server actually sends, so if the server sends a different shape, TypeScript will not catch it at compile time because the cast overrides the any type. Validating the shape at runtime is a separate step you add when the API is untrusted or unstable.
When you do not control the interface at the call site, TypeScript gives you utilities to derive it. ReturnType extracts a function’s return type, Awaited unwraps the promise that an async function returns, and indexing with [number] pulls the element type out of an array, as shown in the async function return type trick:
type User = Awaited<ReturnType<typeof fetchUser>>;
Checking response.ok and catching failures
Two errors can come out of a fetch call, and they need different handling. A network failure makes the promise reject, which your try/catch catches. An HTTP error status resolves normally, so the only way to catch it is to check response.ok yourself and throw.
The standard pattern is to throw when response.ok is false before parsing the body:
async function getPosts(): Promise<Post[]> {
const response = await fetch("https://api.example.com/posts");
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json() as Post[];
}
If you skip the response.ok check, the code never branches on HTTP error statuses, so an HTTP error response that returns an HTML error page will flow into response.json and likely throw a confusing parse error instead of a clear status message. For more on separating the two failure modes, see handling fetch errors in frontend applications.
If you throw inside an async function and nothing catches it, the function returns a rejected promise, and an unhandled rejection triggers a warning and can crash the process in newer Node versions. Wrapping the awaits in try/catch is the way to handle promise rejections from async/await. The caller then decides what to do:
try {
const posts = await getPosts();
renderPosts(posts);
} catch (error) {
showError(error);
}
In an Express route handler, the same catch block passes the error to next(err), which lets Express error-handling middleware respond with the error’s status code or a default 500.
A generic typed fetch wrapper for repeated calls
When many functions in an app call fetch, the response.ok check and the error throw repeat everywhere. A small generic wrapper removes the repetition. The wrapper accepts a type argument that the caller supplies for the expected response, and returns a promise of that type.
async function get<T>(path: string): Promise<T> {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json() as T;
}
const user = await get<User>(`https://api.example.com/users/${id}`);
The same idea works for POST. The wrapper takes a body, serializes it with JSON.stringify, sets the Content-Type header, and returns the parsed response, as demonstrated in this fetch, async/await, and TypeScript gist:
async function post<T>(path: string, body: unknown): Promise<T> {
const response = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json() as T;
}
const created = await post<{ id: number }>("https://api.example.com/posts", {
title: "Hello",
body: "Content",
});
Typing the body as unknown instead of any keeps the payload checked: the compiler enforces that whatever you pass can be serialized, and the interface for the response stays explicit at the call site. For a fuller treatment of this wrapper, see building a typed fetch wrapper in TypeScript.
Avoiding stale state and orphaned requests
In a React component, the async flow creates a timing hazard. The component calls fetch, the user navigates away, and the component unmounts before the server responds. When the promise settles, the code calls setState on a component that no longer exists, or, worse, a newer request for a different id resolves after the older one and overwrites the newer data in state. The older response arrives last and shows stale data.
AbortController is the built-in API that lets you cancel a fetch. You create a controller, pass its signal into the fetch call, and call controller.abort to stop the request. The signal links the controller to the request; when you call abort, fetch rejects the pending promise with an AbortError. In a React hook you abort on cleanup, which runs when the component unmounts or when the dependency changes, as recommended in this GitHub discussion on async state with cancellation:
function useUser(id: number) {
const [user, setUser] = useState<User | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(`https://api.example.com/users/${id}`, {
signal: controller.signal,
});
if (!response.ok) throw new Error(`Status ${response.status}`);
setUser(await response.json() as User);
} catch (err) {
if (err instanceof Error && err.name !== "AbortError") {
setError(err);
}
}
}
load();
return () => controller.abort();
}, [id]);
return { user, error };
}
The check on err.name!== "AbortError" is what keeps cancellation from being reported as a failure. When the cleanup calls abort, the in-flight fetch rejects, and that rejection lands in the catch block. Without the name check, the hook would set an error state every time a request gets canceled, which is normal behavior, not a bug. For a deeper look, canceling fetch requests with AbortController in TypeScript covers the API in more detail.
You can also use the same controller for a timeout. Start a setTimeout that calls controller.abort after a few seconds, and the request stops if the server is slow. Some wrappers translate the resulting AbortError into a clearer timeout message: catch the error, and if its name is AbortError, throw a new Error("Timeout") instead, as shown in this fetch wrapper with AbortController.
Why async/await beats nested callbacks
The older style of asynchronous code passes a callback into each operation, so work that depends on the previous step nests one level deeper each time. Callback-based APIs produce pyramids of indentation that are hard to read, especially when you need data from an earlier request to build the next one. Async/await reads like normal top-to-bottom code and lets you assign each awaited result to a named variable, which is the practical advantage described in the async/await over callbacks comparison.
Under the hood await still relies on promises. The benefit is the shape of the code, not a different mechanism. If you are in Node and a callback-based API is available alongside a promise-based one, prefer the promise version, such as the fs/promises module, and wrap its awaits in try/catch the same way you wrap fetch.