TypeScript · Lesson 36 of 42
Typing promises and async functions
Type asynchronous code with Promise<T>, async and await, run promises in parallel with Promise.all, and avoid the classic mistakes of a missing await.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will type asynchronous code correctly: functions that return promises, async and await, and running several operations at once. Almost every real program waits for something, such as a file, a network request or a timer, so this lesson ties TypeScript to how modern JavaScript really works.
Promise
A promise stands for a value that will arrive later. Its type says what the value will be: Promise<number> will eventually produce a number. Here is a helper that waits, which this lesson reuses:
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getNumber(): Promise<number> {
return new Promise(resolve => setTimeout(() => resolve(42), 10));
}
getNumber().then(n => console.log(n + 1));43Promise<void> means "completes later, with no useful value". In .then(n => ...), n is a number, because the compiler follows the promise's type argument.
async and await
An async function always returns a promise, so you annotate the result as Promise<T>, where T is the type of the value you return:
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchPrice(item: string): Promise<number> {
await delay(10);
return item === "pen" ? 2.5 : 9.99;
}
async function main(): Promise<void> {
const price = await fetchPrice("pen");
console.log(price.toFixed(2));
}
main();2.50Inside main, await fetchPrice("pen") unwraps Promise<number> to a plain number, so toFixed works. If the function returned a string, the Promise<number> annotation would reject it, exactly like any return type.
The classic mistake: missing await
If you forget await, you are left holding the promise itself. TypeScript catches this in most places:
async function fetchPrice(): Promise<number> {
return 2.5;
}
async function main() {
const price: number = fetchPrice();
console.log(price);
}example.ts(6,9): error TS2322: Type 'Promise<number>' is not assignable to type 'number'.The same idea applies to conditions: if (isValid()) with an async function is always true because a promise is truthy, which a type-aware linter (a later lesson) can flag. Using await outside an async function is also an error:
async function fetchPrice(): Promise<number> {
return 2.5;
}
function main() {
const price = await fetchPrice();
}example.ts(6,17): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.Running things in parallel
Awaiting operations one after another makes them run in sequence. When they do not depend on each other, start them together with Promise.all, which waits for all and returns the results in order. TypeScript keeps each result's own type:
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getCount(): Promise<number> {
await delay(20);
return 3;
}
async function getName(): Promise<string> {
await delay(10);
return "Asha";
}
async function main(): Promise<void> {
const [count, name] = await Promise.all([getCount(), getName()]);
console.log(`${name} has ${count.toFixed(1)}`);
}
main();Asha has 3.0count is a number and name is a string, because the result is the tuple [number, string]. If one promise rejects, Promise.all rejects immediately. When you need every outcome even if some fail, use Promise.allSettled, whose results are a union describing success or failure:
async function main(): Promise<void> {
const results = await Promise.allSettled([
Promise.resolve(1),
Promise.reject(new Error("failed")),
]);
for (const result of results) {
if (result.status === "fulfilled") {
console.log("ok", result.value);
} else {
console.log("failed", (result.reason as Error).message);
}
}
}
main();ok 1
failed failedEach result is a discriminated union with status as its tag, so narrowing works exactly as in the earlier lesson.
Errors in async code
A rejected promise throws at the await, so use try and catch as with ordinary code. The next lesson covers how to type the caught error safely. A function that may fail can also return a result type, as the discriminated unions lesson showed, instead of throwing.
Awaited
The utility type Awaited<T> computes what you get after await, unwrapping nested promises. Combine it with ReturnType to name the result of an async function without repeating it:
async function loadUser() {
return { id: 1, name: "Asha" };
}
type User = Awaited<ReturnType<typeof loadUser>>;
const user: User = { id: 2, name: "Ben" };
console.log(user);{ id: 2, name: 'Ben' }Common mistakes
Forgetting await. You get a promise where you expected a value. Annotating the variable usually makes the compiler catch it.
Awaiting in a loop when the work is independent. Use Promise.all to run things together.
Writing Promise
Using async without await. The function still returns a promise, which may not be what you intended.
Leaving promises unhandled. A promise you never await can fail silently. Linting rules (a later lesson) can catch these.
Exercise
Write async function fetchUser(id: number): Promise<{ id: number; name: string }> that waits briefly and returns a user. Write async function fetchAll(ids: number[]) that uses Promise.all with map to fetch every user at once. Then write one version that forgets an await and read the error. Finally, derive the user type with Awaited and ReturnType.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.