HardEvent Loop & Batching💻 Output Question

Suspense — component throws Promise, boundary catches it

💡

Hint

Suspense works because components CAN throw Promises. React catches the thrown Promise, shows the fallback, and re-renders when it resolves. This is the 'throw to suspend' protocol.

What does this output?

// Simplified Suspense simulation
const cache = new Map();

function fetchData(key) {
  if (cache.has(key)) return cache.get(key); // resolved — return value
  const promise = new Promise(resolve =>
    setTimeout(() => { cache.set(key, 'data:' + key); resolve(); }, 10)
  );
  throw promise; // not resolved — throw Promise
}

function trySuspend(key) {
  try {
    const data = fetchData(key);
    return data;
  } catch (e) {
    if (e instanceof Promise) return 'loading...';
    throw e;
  }
}

console.log(trySuspend('users'));  // cache miss

// Simulate promise resolving
setTimeout(() => {
  console.log(trySuspend('users')); // cache hit
}, 20);

Correct Output

loading...
data:users

Why this output?

Explanation: First call: cache miss, fetchData throws a Promise, caught and returns 'loading...'. After timeout, cache is populated. Second call: cache hit, returns 'data:users'.

Key Insight: Suspense works because components CAN throw Promises. React catches the thrown Promise, shows the fallback, and re-renders when it resolves. This is the 'throw to suspend' protocol.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz