Lesson 2 of 7
async / await - Typed Async Functions
`async` functions always return `Promise<T>` - TypeScript infers T from the return value. `await` unwraps a `Promise<T>` to `T`. The combination makes asynchronous code read synchronously while remaining fully type-safe at every step.
async/await - Patterns & Error Handling
// ── Basic async/await ────────────────────────────────────────
// Return type inferred as Promise<Task | null>:
async function getTask(id: number): Promise<Task | null> {
const res = await fetch(`/api/tasks/${id}`);
if (!res.ok) return null;
const data: unknown = await res.json();
return isTask(data) ? data : null; // validates before returning
}
// ── try/catch in async functions ──────────────────────────────
async function createTask(input: CreateTaskInput): Promise<Task> {
try {
const res = await fetch("/api/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
const errBody: unknown = await res.json();
const message =
typeof errBody === "object" && errBody !== null && "message" in errBody
? String((errBody as { message: unknown }).message)
: `HTTP ${res.status}`;
throw new Error(message);
}
const data: unknown = await res.json();
if (!isTask(data)) throw new Error("Invalid task response shape");
return data;
} catch (error: unknown) {
if (error instanceof Error) throw error; // re-throw typed errors
throw new Error("Unknown error creating task"); // wrap unknown errors
}
}
// ── Result-type pattern - no thrown errors ────────────────────
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function safeGetTask(id: number): Promise<Result<Task>> {
try {
const task = await getTask(id);
if (!task) return { ok: false, error: new Error(`Task ${id} not found`) };
return { ok: true, value: task };
} catch (error: unknown) {
return {
ok: false,
error: error instanceof Error ? error : new Error("Unknown error"),
};
}
}
// Usage - caller never needs try/catch:
const result = await safeGetTask(1);
if (result.ok) {
console.log(result.value.title);
} else {
console.error(result.error.message);
}
// ── Async immediately invoked ─────────────────────────────────
void (async () => {
const task = await getTask(1);
console.log(task?.title);
})();Common Mistakes
- Using `await` without try/catch - unhandled async errors surface as unhandled promise rejections. Either wrap in try/catch or use the Result pattern.
- Forgetting `await` before async function calls - without `await`, you're working with a `Promise<T>`, not `T`. TypeScript will catch this when you try to access `.title` on a `Promise<Task>`.
- Returning `Promise<void>` from async functions that should return data - async functions that update or delete often return `Promise<void>`, but callers may need confirmation. Consider returning the updated entity.
Tip
Tip
Practice async await Typed Async Functions in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for async / await - Typed Async Functions
Practice Task
Note
Practice Task - (1) Write a working example of async await Typed Async Functions from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with async await Typed Async Functions is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- `async` functions always return `Promise<T>` - TypeScript infers T from the return value.
- Using `await` without try/catch - unhandled async errors surface as unhandled promise rejections. Either wrap in try/catch or use the Result pattern.
- Forgetting `await` before async function calls - without `await`, you're working with a `Promise<T>`, not `T`. TypeScript will catch this when you try to access `.title` on a `Promise<Task>`.
- Returning `Promise<void>` from async functions that should return data - async functions that update or delete often return `Promise<void>`, but callers may need confirmation. Consider returning the updated entity.
Finished this lesson?