JavaScript Async/Await - Exercise 2

Return the final value with return. The async function wraps that value in a fulfilled promise automatically. That lets later code use the value without manually nesting Promise callbacks.

javascript

async function totalPrice(price, tax) {
  return price + tax;
}

totalPrice(80, 20).then(console.log); // 100

The async function pauses until the promise fulfills, then await evaluates to the resolved value. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

async function showStatus() {
  const status = await Promise.resolve('ready');
  console.log(status); // 'ready'
}

A rejected promise makes await throw the rejection reason at that line, so control moves to catch if one exists. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

async function loadData() {
  try {
    await Promise.reject(new Error('Request failed'));
  } catch (error) {
    console.error(error.message);
  }
}

The caller can either use try...catch with await or attach .catch() to the returned promise. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

async function parseJson() {
  throw new Error('Invalid JSON');
}

parseJson().catch(error => console.error(error.message));

Use sequential await calls when a later step depends on an earlier result or when the order must be preserved. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

const user = await fetchUser(userId);
const orders = await fetchOrders(user.id);

console.log(orders);

Use Promise.all() when operations do not depend on one another and can start at the same time. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

const [profile, settings] = await Promise.all([
  fetchProfile(),
  fetchSettings()
]);

Promise.all() rejects as soon as one input promise rejects, so the combined await throws that first failure. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

try {
  await Promise.all([fetchUser(), Promise.reject(new Error('Failed'))]);
} catch (error) {
  console.error(error.message);
}

Race the request against a promise that rejects after a delay, or use an AbortController when you need to cancel the request itself. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

const timeout = new Promise((_, reject) => {
  setTimeout(() => reject(new Error('Timed out')), 3000);
});

const result = await Promise.race([fetchData(), timeout]);

Preserving context explains which operation failed and makes logs and user-facing messages easier to understand. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

try {
  await saveProfile(profile);
} catch (error) {
  throw new Error(`Saving profile failed: ${error.message}`);
}

Put cleanup in a finally block so it runs after both success and failure. The surrounding async function resumes after the awaited Promise settles, so the result is available on the next line.

javascript

setLoading(true);
try {
  await fetchReport();
} finally {
  setLoading(false);
}
All sections expanded. Activate the control to collapse all sections.