async await notes 2026-09-01

By Xah Lee. Date: .
work in progress

6. Async / Await (Syntactic Sugar over Promises)

async/await makes asynchronous code look synchronous.

async function getUserAndOrders(userId) {
  try {
    const user = await fetchUserData(userId);
    console.log("User:", user.name);

    const orders = await fetchUserOrders(user.id);
    console.log("Orders:", orders);

    return orders;
  } catch (error) {
    console.error("Failed:", error.message);
    throw error; // re-throw if you want the caller to handle it
  }
}

// Calling an async function returns a Promise
getUserAndOrders(1)
  .then(orders => console.log("Done"))
  .catch(err => console.error(err));

Key points about async/await

const [user, posts, comments] = await Promise.all([
  fetchUser(1),
  fetchPosts(1),
  fetchComments(1)
]);
work in progress

async await

You can also use the modern async/await syntax (recommended for most code):

async function run() {
  try {
    const result = await myPromise;
    console.log("Success:", result);
  } catch (error) {
    console.error("Error:", error.message);
  } finally {
    console.log("Cleanup");
  }
}

run();