Find a subject or note

13 results found

JavaScriptArray Methods, Loop Mechanics & The Async Trap

Mastering slice vs splice, search & reduce patterns, loop intent (for...in vs for...of vs map), and the async forEach trap.

JavaScriptasync / await & Modern Asynchronous Flow

Mastering async functions, the non-blocking await keyword, error handling with try/catch, and avoiding performance waterfalls.

JavaScriptcall(), apply(), bind() (Controlling this)

How to explicitly control function execution context in JavaScript using call, apply, and bind.

JavaScriptErrors, try/catch & Defensive Design

Understanding built-in error types, the Error object, custom error classes, async handling, and defensive validation patterns.

JavaScriptThe Event Loop

How JavaScript coordinates synchronous code, the Call Stack, Microtask Queue, and Macrotask Queue.

JavaScriptFetch API, HTTP & Web APIs

HTTP fundamentals, URLSearchParams, response handling, CORS, AbortController, and production service layers.

JavaScriptFirst-Class Functions, Callbacks & Closures

How first-class functions, callbacks, and closures connect to form the foundation of modern JavaScript.

JavaScriptObject Utilities (keys, values, entries, fromEntries)

How Object.keys, Object.values, Object.entries, and Object.fromEntries bridge objects and arrays in JavaScript.

JavaScriptPromises & Promise Combinators

Understanding asynchronous execution, Promise lifecycles, error propagation, and Promise combinators (all, allSettled, race, any).

JavaScriptReturn, Scope & Hoisting in Functions

How return statements, lexical scope, and hoisting determine how functions execute in JavaScript.

JavaScriptSecurity Basics: XSS & Safe DOM Rendering

Cross-Site Scripting (XSS) mechanics, safe DOM manipulation, innerHTML vs textContent, and the validation vs sanitization pipeline.

JavaScriptShallow vs. Deep Copy (Spread Pitfalls & JSON Limits)

Understanding object references, shallow copy pitfalls with spread, JSON limitations, and structuredClone.

JavaScriptWeb Storage: localStorage, sessionStorage & Cookies

Client-side storage mechanisms in JavaScript: comparing localStorage, sessionStorage, and Cookies for interview prep.

Promises & Promise Combinators

Because JavaScript executes in a single-threaded runtime environment, long-running operations (network requests, disk I/O, timers) cannot block the thread without freezing the entire browser or server.

While callbacks were the original solution for non-blocking code, deeply nested callbacks created Callback Hell (the "Pyramid of Doom"). Promises replaced this by introducing structured, flat async pipelines based on a simple mental model:

$$\text{From: “What runs inside what?”} \longrightarrow \text{To: “What happens next?”}$$

Diagram illustrating Promise states, consumption pipeline, and combinators matrix
The three Promise states, the .then()/.catch() chaining pipeline, and the four Promise combinators.

1. Promise Basics: The Three States & The Executor

A Promise has exactly three states:

  1. Pending: The initial state; the asynchronous operation is still executing.
  2. Fulfilled: The operation succeeded; resolve(value) was called.
  3. Rejected: The operation failed; reject(error) was called.

The Executor Function

When creating a new Promise((resolve, reject) => ...), the executor function runs immediately and synchronously. Calling resolve or reject settles the promise permanently; subsequent calls are silently ignored.

promise-creation.js
// Creating a Promise with the Executor function
const fetchUserData = new Promise((resolve, reject) => {
  const networkSuccess = true;

  // Asynchronous operation (e.g. API request simulation)
  setTimeout(() => {
    if (networkSuccess) {
      resolve({ id: 1, name: "Ali", role: "admin" });
    } else {
      reject(new Error("Network connection failed"));
    }
  }, 100);
});

// Consuming with .then(), .catch(), and .finally()
fetchUserData
  .then(user => {
    console.log("1. User fetched:", user.name);
    return user.role; // Passes role to the next .then()
  })
  .then(role => {
    console.log("2. Role is:", role);
  })
  .catch(err => {
    console.error("Error caught:", err.message);
  })
  .finally(() => {
    console.log("3. Cleanup: spinner stopped");
  });
Values returned from .then() are wrapped in a new Promise and forwarded to the next link in the chain.

2. Consuming Promises: .then(), .catch(), .finally()

  • .then(onFulfilled): Executes when the Promise resolves. If you return a value, the next .then() receives it; if you return another Promise, JavaScript waits for it automatically.
  • .catch(onRejected): Centralized error boundary for the entire preceding chain.
  • .finally(onFinally): Always runs upon settlement for cleanup. Receives no arguments and does not modify the settled value.

3. Error Propagation in Promise Chains

Unlike manual callback trees where each step requires manual error checking, Promises feature automatic rejection propagation:

If an error is thrown or a promise rejects anywhere in a .then() chain, execution immediately skips all subsequent .then() blocks and jumps directly to the nearest .catch().

promise-error-propagation.js
function step1() { return Promise.resolve("Data 1"); }
function step2() { throw new Error("Step 2 failed!"); }
function step3() { return Promise.resolve("Data 3"); }

// Error skips step3 and jumps directly to .catch()
step1()
  .then(data => {
    console.log("Step 1 done:", data);
    return step2();
  })
  .then(data => {
    console.log("Step 3 done:", data); // SKIPPED!
  })
  .catch(err => {
    console.log("Catch handled:", err.message); // Handles Step 2 error!
  })
  .then(() => {
    console.log("Chain can still continue after .catch()");
  });
A single .catch() at the bottom handles errors from all previous stages.

4. The 4 Promise Combinators

When managing multiple concurrent asynchronous operations, JavaScript provides four specialized combinators:

  1. Promise.all() (All-or-Nothing): Waits for all to fulfill. If any promise rejects, it rejects immediately with that error.
  2. Promise.allSettled() (Full Visibility): Waits for all to finish, whether fulfilled or rejected. Never rejects.
  3. Promise.race() (Fastest Settles): Resolves or rejects as soon as the first promise settles.
  4. Promise.any() (First Success): Resolves as soon as the first promise fulfills. Rejects only if all fail (yielding an AggregateError).
promise-combinators.js
const fastSuccess = Promise.resolve("Fast (10ms)");
const slowSuccess = new Promise(r => setTimeout(() => r("Slow (200ms)"), 200));
const fastFail = Promise.reject(new Error("Fast Failure"));

// 1. Promise.all -> All-or-nothing (Fails fast if any promise rejects)
Promise.all([fastSuccess, slowSuccess])
  .then(res => console.log("Promise.all:", res)); // ["Fast (10ms)", "Slow (200ms)"]

// 2. Promise.allSettled -> Waits for all, NEVER rejects
Promise.allSettled([fastSuccess, fastFail])
  .then(res => console.log("Promise.allSettled:", res));
  // [{ status: "fulfilled", value: "Fast (10ms)" }, { status: "rejected", reason: Error }]

// 3. Promise.race -> First to settle wins (fulfilled or rejected)
Promise.race([fastSuccess, slowSuccess])
  .then(winner => console.log("Promise.race winner:", winner)); // "Fast (10ms)"

// 4. Promise.any -> First SUCCESS wins (ignores errors unless ALL fail)
Promise.any([fastFail, slowSuccess])
  .then(firstSuccess => console.log("Promise.any:", firstSuccess)); // "Slow (200ms)"
Choose combinators according to whether you need all results, fastest result, or first success.
The 4 Promise Combinators Matrix

Combinator

Success Condition

Failure Condition

Settled Value Format

Primary Use Case

Promise.all()

ALL promises fulfill

ANY promise rejects (fails fast)

Array of values [val1, val2]

Dependent parallel tasks where all are required

Promise.allSettled()

Always fulfills (all complete)

Never rejects

Array of objects [{status, value/reason}]

Independent tasks where partial success is acceptable

Promise.race()

First promise fulfills

First promise rejects

Single value or error of the fastest

Request timeouts, fastest mirror response

Promise.any()

First promise fulfills

ALL promises reject (AggregateError)

Single value of first successful task

Redundant endpoints, fallback service providers

Think it throughActivity 1: What is the exact console output of this Promise chain?
Promise.resolve(1)
  .then(x => x + 1)
  .then(x => { throw new Error('Failed at ' + x); })
  .catch(err => 10)
  .then(x => x * 2)
  .then(console.log);

Output: 20

Explanation:

  1. Resolves with 1 $\rightarrow$ next .then() returns 2.
  2. Second .then() throws Error('Failed at 2') $\rightarrow$ skips down to .catch().
  3. The .catch() intercepts the error and returns a replacement value 10.
  4. Returning 10 fulfills the chain! The subsequent .then() receives 10, multiplies by 2, and logs 20.
Think it throughActivity 2: Predict how Promise.all and Promise.any behave with mixed rejections:
const p1 = Promise.reject('Error A');
const p2 = Promise.resolve('Success B');

Promise.all([p1, p2]).catch(console.log);
Promise.any([p1, p2]).then(console.log);

Output: Error A (from Promise.all) Success B (from Promise.any)

Why?

  • Promise.all requires all to succeed and fails immediately on p1.
  • Promise.any ignores p1's rejection and waits for the first fulfillment, resolving with p2.