Summary - async/await
Build a flow that fetches data from two APIs in sequence and combines them using async/await.
async/await summary
async/await turns promise-based asynchronous code into something that looks synchronous. An async function always returns a promise; await waits for a promise's result. Errors are caught with try/catch; independent tasks run in parallel with Promise.all; async iterables are walked with for await...of.
In this summary you will build a flow that combines all of them: first two API calls in sequence, then two parallel data loads.
Exercise Two API calls in sequence
Write async function loadProfile(). Inside a try block, first call await fetchUser() and assign to user, then await fetchPosts(user.id) and assign to posts. Add a catch (err) block that logs the error with console.error(err).
Show example solution
async function loadProfile() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
} catch (err) {
console.error(err);
}
}
Exercise Load data in parallel
Write async function loadParallel(). Inside it, call await Promise.all([fetchProfile(), fetchSettings()]) and destructure the result as [profile, settings].
Show example solution
async function loadParallel() {
const [profile, settings] = await Promise.all([
fetchProfile(),
fetchSettings()
]);
}
Test yourself
-
Match async/await concepts
- async function
- always returns a promise
- await
- waits for the promise's result
- try/catch
- catches an async error
- Promise.all
- enables parallel execution
- for await...of
- walks an async iterable
-
Which one is the fastest?
// A: sequential const a = await p1(); const b = await p2(); // B: parallel const [a, b] = await Promise.all([p1(), p2()]);- Option B is faster
- Option A is faster
- Both finish in equal time
- Time does not depend on the promises
Show answer
Option B is faster — Correct! Parallel execution shortens total time for independent operations.