Async Programming Basics
Async Programming Basics
Section titled βAsync Programming BasicsβWhat it means
Section titled βWhat it meansβJavaScript is single-threaded, but most real work (network requests, timers, file I/O) is asynchronous β it happens in the background without blocking the rest of the program. JavaScript has evolved three ways to handle async results: callbacks (oldest), Promises (an object representing a future value), and async/await (syntax sugar over Promises that reads like synchronous code).
Examples
Section titled βExamplesβ// Callback style (older)setTimeout(() => console.log("1 second later"), 1000);
// Promise stylefetch("/api/user") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
// async/await style (modern, most readable)async function getUser() { try { const response = await fetch("/api/user"); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }}Common mistake
Section titled βCommon mistakeβForgetting await when calling an async function β you get the Promise object itself instead of the resolved value, since an async function always returns a Promise.
async function getUser() { return { name: "Alice" };}
const user = getUser();console.log(user.name); // undefined -- `user` is a Promise, not the object!
const user = await getUser(); // must be inside an async functionconsole.log(user.name); // "Alice" -- correctQuick practice
Section titled βQuick practiceβ-
What does an
asyncfunction always return?Answer
APromiseβ even if you write a plainreturn value;, JavaScript wraps it in a resolved Promise automatically. -
What happens if you forget
awaitbefore an async function call?Answer
You get the pendingPromiseobject itself instead of the resolved value β you have toawaitit or chain.then()to get the actual result. -
How do you handle errors in
async/awaitcode?Answer
Wrap theawaitcalls in atry/catchblock, same as synchronous error handling.