Module 8: Asynchronous JavaScript
async and await
Write promise-based code in a sequential style while preserving error handling.
An async function always returns a promise. The await keyword pauses that async function until a promise settles, then produces its fulfilled value or throws its rejection. It does not block the entire JavaScript runtime while waiting.
async function loadProfile() {
const profile = await Promise.resolve({ name: "Asha" });
return profile;
}
loadProfile().then(console.log);
Inside an async function, try...catch can handle rejected operations in a sequential style:
async function loadData() {
try {
const result = await Promise.resolve("Loaded");
return result;
} catch (error) {
console.error("Could not load data", error);
throw error;
}
}
Catch errors where you can recover or add context. If you cannot recover, rethrowing may let the caller decide what to do. Avoid catching an error and returning a fake success value without making that choice explicit.
Sequential versus parallel#
Awaiting independent tasks one after another makes their total duration add up. When tasks do not depend on each other, start them together and await Promise.all:
const [user, settings] = await Promise.all([
fetchUser(),
fetchSettings(),
]);
Practice#
Convert a promise chain into an async function. Add a try...catch block and explain whether two independent tasks should run sequentially or concurrently.