← Lesson
BitWithBite
JavaScript · Quick Reference

Lesson 12 — Fetch API & Async JavaScript Cheat Sheet

JavaScript
In one line: JavaScript runs in a single thread — it can only do one thing at a time. If you write code that blocks this thread (say, waiting 3 seconds for a server response), the enti...

Key Ideas

1Why Async Matters. JavaScript runs in a single thread — it can only do one thing at a time. If you write code that blocks this thread (say, waiting 3 seconds for a server response)...
2Callbacks. A callback is a function you pass as an argument to another function, to be called once an async operation completes. They were the original solution to async JavaScri...
3Promises. A Promise is an object representing the eventual completion or failure of an async operation. It's a placeholder for a value that doesn't exist yet. Promises have thre...
4async / await. async/await is syntactic sugar built on top of Promises. It lets you write async code that looks synchronous, which is far easier to read and debug. An async function ...
5The Fetch API. The Fetch API is the browser's built-in tool for making HTTP requests. It replaced the older XMLHttpRequest and returns a Promise, making it perfect to use with async/...

Code Examples

// Simulating async operations with setTimeout function getUser(id, callback) { setTimeout(() => { callback({ id, name: 'Alice' }); }, 500); } function getOrders(userId, callback) { setTimeout(() => { callback([{ id: 1, item: '...
// Creating a Promise manually const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('Data loaded!'); // fulfilled } else { reject(new Error('Something went wrong')); // rejected } })...
// Mark the function with 'async' async function loadUserData() { // 'await' pauses HERE until the promise resolves const user = await getUser(1); console.log(user.name); // Alice const orders = await getOrders(user.id); console.lo...