❀ Like
πŸ”– Save
πŸ”— Share
Eric Hu
Eric Hu

JavaScript Async/Await Syntax

@thedevspaceio

⏱️ Async/Await: JavaScript's Gift to Readability

Let’s be honest, the callback syntax for async code was a nightmare, and Promises with their .then() chains could still get messy fast.

Then came async/await. And everything changed.

But here’s the thing: it’s not just syntactic sugar. It's a fundamental shift in how we write asynchronous code.

πŸ”‘ In this cheatsheet, we'll cover:

βœ… async – marks a function as asynchronous, always returns a Promise
βœ… await – pauses execution until the Promise settles (without blocking the event loop)
βœ… try/catch – the familiar, intuitive way to handle errors (no more .catch() chaining)

#JavaScript #AsyncAwait #NodeJS #WebDevelopment #CodingTips #Programming #SoftwareEngineering #CleanCode #Frontend #Backend #TechLearning


async and await are syntactic sugar created to make Promises easier to read. They let you write asynchronous code that feels more like synchronous code.

async functions

async declares a function that always returns a Promise. If you return a non-promise value, it will be wrapped in Promise.resolve.

js
async function greet() {
  return "Hello"; // Equivalent to: return Promise.resolve("Hello");
}
 
greet().then((message) => console.log(message)); // "Hello"

If an async function throws an error, the returned Promise is rejected.

js
async function fail() {
  throw new Error("Oops");
}
 
fail().catch((error) => console.error(error.message)); // "Oops"

await keyword

await pauses the execution of an async function until the Promise resolves or rejects.

js
async function getUser(id) {
  const response = await fetch(`/api/users/${id}`);
  const user = await response.json();
  return user;
}

await only works inside async functions or at the top level of modules.


Error handling with try...catch

Wrap awaited calls in try...catch to handle errors:

js
async function loadUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
 
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
 
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error("Failed to load user:", error.message);
  }
}

Use finally for cleanup logic.

js
async function fetchData() {
  try {
    const data = await fetch("/api/data");
    return data;
  } catch (error) {
    console.error(error);
  } finally {
    console.log("Request finished");
  }
}

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io