Chapters: JavaScript HTML & CSS JSON XML YAML Go Java ← Full TOC

← JavaScript Index

⏳ Promises & Async — Async/await, Promise, fetch — asynchronous JavaScript

JavaScript is single-threaded and uses an event loop. Promise represents a future value. async/await is syntactic sugar over Promises that makes async code look synchronous. fetch is the built-in HTTP client.

📋 Methods & APIs

NameSignature / SyntaxDescription
Promisenew Promise((resolve, reject) => {})Create a Promise
Promise.resolvePromise.resolve(value) → PromiseCreate immediately-resolved Promise
Promise.rejectPromise.reject(error) → PromiseCreate immediately-rejected Promise
Promise.allPromise.all([p1,p2,p3]) → Promise<[]>Resolve when ALL resolve; reject if any reject
Promise.allSettledPromise.allSettled([p1,p2]) → PromiseResolve when ALL settle (fulfilled or rejected)
Promise.racePromise.race([p1,p2]) → PromiseResolve/reject with whichever settles first
Promise.anyPromise.any([p1,p2]) → PromiseResolve with first fulfilled; reject if all reject
.then.then(onFulfilled, onRejected)Chain fulfilled/rejected handlers
.catch.catch(onRejected)Handle rejection
.finally.finally(fn)Run fn regardless of outcome
async functionasync function f() {}Function that always returns a Promise
awaitconst x = await promisePause until Promise settles
try/catch with awaittry { await fn() } catch(e) {}Handle async errors
fetchfetch(url, options) → Promise<Response>Built-in HTTP client
response.jsonresponse.json() → Promise<any>Parse response body as JSON
response.textresponse.text() → Promise<string>Parse response body as text
response.okresponse.ok → boolTrue if status 200-299
response.statusresponse.status → numberHTTP status code
AbortControllernew AbortController()Cancel fetch requests
setTimeoutsetTimeout(fn, ms) → idRun fn after delay
setIntervalsetInterval(fn, ms) → idRun fn repeatedly every ms
clearTimeoutclearTimeout(id)Cancel scheduled timeout
queueMicrotaskqueueMicrotask(fn)Schedule fn as microtask (before next macro)
for await...offor await (const x of asyncIterable)Iterate async iterables

💡 Example

Run with node script.js or save as HTML and open in browser.

// Async/Await & Promises
// --- Basic Promise ---
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const fetchUser = async (id) => {
  await delay(10);  // simulate network
  if (id <= 0) throw new Error(`Invalid id: \${id}`);
  return { id, name: `User\${id}`, role: id === 1 ? 'admin' : 'user' };
};

// --- async/await with error handling ---
async function main() {
  // Sequential
  try {
    const user = await fetchUser(1);
    console.log('User:', user);
  } catch (e) {
    console.error('Error:', e.message);
  }

  // Parallel with Promise.all
  const [u1, u2, u3] = await Promise.all([fetchUser(1), fetchUser(2), fetchUser(3)]);
  console.log('All users:', [u1, u2, u3].map(u => u.name));

  // Promise.allSettled — handles mixed success/failure
  const results = await Promise.allSettled([
    fetchUser(1), fetchUser(-1), fetchUser(3)
  ]);
  results.forEach((r, i) => {
    if (r.status === 'fulfilled') console.log(`  ✅ \${i}: \${r.value.name}`);
    else                          console.log(`  ❌ \${i}: \${r.reason.message}`);
  });

  // Race (first wins)
  const fast = await Promise.race([delay(50).then(()=>'slow'), delay(10).then(()=>'fast')]);
  console.log('Race winner:', fast);  // fast

  // Real fetch example (Node 18+ or browser)
  try {
    const res  = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const data = await res.json();
    console.log('Post title:', data.title.substring(0, 40));
  } catch (e) {
    console.log('Fetch error (offline?):', e.message);
  }
}

main().catch(console.error);
// node script.js  (Node 18+ has built-in fetch)

← Arrays & Iteration  |  🏠 Index  |  DOM & Browser →