ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Async Cheatsheet

@thedevspaceio

ā³ JavaScript Async Cheatsheet

Asynchronous programming lets JavaScript handle tasks like network requests and timers without blocking the main thread.

āœ… Callbacks āœ… Promises āœ… then / catch / finally āœ… async / await āœ… Async iterators

#javascript #async #promises #await #callbacks #eventloop #webdev #frontend #coding #tips


JavaScript is single-threaded, but async programming lets you handle tasks like network requests, timers, and file I/O without blocking the main thread.

It allows operations run in the background and resume once they complete.


Callbacks

The original pattern for async code in JavaScript.

js
function fetchData(callback) {
  setTimeout(() => {
    callback("data loaded");
  }, 1000);
}
 
fetchData((message) => {
  console.log(message); // "data loaded"
});

async intro


It works, but nested callbacks can lead to "callback hell".

js
getData((data) => {
  processData(data, (processed) => {
    saveData(processed, (result) => {
      console.log(result);
    });
  });
});

Promises

A Promise represents a value that may not exist yet but will resolve or reject in the future.

It is a better syntax for writing async code.

js
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 1000);
});
 
promise.then((value) => console.log(value)); // "Success!"

A promise can have one of three states:

StateDescription
pendingInitial state, neither fulfilled nor rejected.
fulfilledThe operation completed successfully.
rejectedThe operation failed.

then / catch / finally

Three promise methods to handle async results. Handle fulfilled, rejected, and settled promises:

js
fetch("https://api.example.com/user")
  .then((response) => response.json()) // Fulfilled
  .then((data) => console.log(data)) // Fulfilled
  .catch((error) => console.error(error)) // Rejected
  .finally(() => console.log("Done")); // Settled, runs regardless of outcome

async / await

Write async code that reads like synchronous code. A even more familiar syntax for handling promises.

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

Use try...catch for error handling.

js
async function loadUser(id) {
  try {
    const user = await getUser(id);
    console.log(user);
  } catch (error) {
    console.error("Failed to load user", error);
  }
}

Async iterators

Use for await...of to iterate over async data sources.

js
async function* generateIds() {
  for (let i = 1; i <= 3; i++) {
    yield await fetch(`/api/users/${i}`).then((r) => r.json());
  }
}
 
for await (const user of generateIds()) {
  console.log(user.name);
}

Full-Stack AI Developer Roadmap

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

@thedevspaceio
www.thedevspace.io