TypeScript Tutorial: Async/Await
Type async functions, Promises, and handle errors in asynchronous TypeScript code.
Typing Async Functions
An `async` function always returns a `Promise<T>`:
```typescript
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error("Not found");
return res.json() as Promise<User>;
}
```
---
Promise Types
```typescript
// Promise that resolves to a string
const p1: Promise<string> = Promise.resolve("hello");
// Promise that resolves to void (no return value)
async function sendEmail(to: string): Promise<void> {
await emailService.send(to);
}
// Promise that might reject
async function divide(a: number, b: number): Promise<number> {
if (b === 0) throw new Error("Division by zero");
return a / b;
}
```
---
Error Handling
TypeScript's `catch` errors are always `unknown` — narrow before using:
```typescript
async function loadData(url: string): Promise<string> {
try {
const res = await fetch(url);
return await res.text();
} catch (error) {
// error is `unknown` — must narrow
if (error instanceof Error) {
console.error(error.message);
}
throw error;
}
}
```
---
Parallel Execution
```typescript
async function loadAll(ids: number[]): Promise<User[]> {
const promises = ids.map(id => fetchUser(id));
return Promise.all(promises); // all run in parallel
}
// With individual error handling:
const results = await Promise.allSettled([
fetchUser(1),
fetchUser(2),
fetchUser(999), // might fail
]);
```
---
Typed Callbacks to Async
```typescript
type AsyncHandler<T> = (value: T) => Promise<void>;
const handleUser: AsyncHandler<User> = async (user) => {
await save(user);
};
```
---
What's Next?
Next: **Modules** — organizing TypeScript code with imports, exports, and module patterns.
What you'll learn in this TypeScript async/await tutorial
This interactive TypeScript tutorial has 11 hands-on exercises. Estimated time: 12 minutes.
- async functions always return Promise — Any function marked `async` returns `Promise<T>`. TypeScript tracks the type inside the Promise.
- await — unwrap Promises — `await` pauses execution until a Promise resolves and unwraps the value. TypeScript knows the unwrapped type.
- Error handling in async code — Errors in async functions are caught with `try/catch`. The caught error is `unknown` — narrow before using it.
- Promise.all — parallel execution — `Promise.all` runs multiple promises in parallel. TypeScript infers the tuple type of the results.
- Promise.allSettled — handle partial failures — `Promise.allSettled` completes even when some promises reject. Each result has a `status` of `fulfilled` or `rejected`.
- Async iteration — for await...of — `for await...of` iterates over async iterables — streams, paginated APIs, or any async generator. TypeScript understands…
- Typed callbacks and event listeners — When working with callbacks and event listeners, TypeScript can infer parameter types from the callback signature.
- Async class methods — typed patterns — Class methods can be async. TypeScript tracks the Promise return type and ensures callers handle the async nature.
- Cancellation with AbortController — Long-running async operations should be cancellable. `AbortController` is the standard web API for this. TypeScript prov…
- Async generators — streaming data — Async generators produce values on demand using `yield`. They're perfect for streaming large datasets, paginated APIs, a…
- Wrapping callbacks as Promises — Many older APIs use callbacks instead of Promises. You can wrap them in typed Promises for use with `async/await`.
TypeScript Async/Await concepts covered
- Typing Async Functions
- Promise Types
- Error Handling
- Parallel Execution
- Typed Callbacks to Async
- What's Next?