Async and Promises
Async and Promises
JavaScript is single-threaded. Long operations (network, timers) are handled asynchronously so the UI does not block.
Callbacks (legacy)
javascriptsetTimeout(() => console.log(\"Later\"), 1000);
Nested callbacks become hard to read (callback hell).
Promises
A Promise represents a value (or error) that will be available later:
javascriptconst p = fetch(\"/api/data\") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
then runs when the promise resolves; catch when it rejects.
async/await
Syntactic sugar over promises. Use in an async function:
javascriptasync function loadData() { try { const res = await fetch(\"/api/data\"); const data = await res.json(); return data; } catch (err) { console.error(err); } }
await pauses the function until the promise settles. Always use try/catch around await if you need to handle errors.