Question Bank
Fetch API and Error Handling Quiz
Difficulty: Medium
Practice the small but easily-bungled `fetch` rituals: real error handling, Promise wrappers around timers, and `Promise.resolve` / `Promise.reject` for branching success states.
Fetch API and Error Handling Quiz
Practice the small but easily-bungled `fetch` rituals: real error handling, Promise wrappers around timers, and `Promise.resolve` / `Promise.reject` for branching success states.
501 views
12
Implement fetchData(url) that performs a fetch, throws on non-2xx responses, parses the body as JSON, and logs the data or error.
Examples
Example 1:
Input: fetchData('/api/items')
Output: logs the parsed JSON, or logs 'There was a problem with your fetch operation: ...' on failure.
Explanation: `fetch` only rejects on network errors; 4xx/5xx come back as resolved responses with `ok: false`, so you must check explicitly.Build a trafficLight() function that, using promises and setTimeout, logs RED then YELLOW then GREEN with delays 3s / 1s / 2s, then repeats forever.
Examples
Example 1:
Input: trafficLight()
Output: RED, (3s) YELLOW, (1s) GREEN, (2s) ----- repeat
Explanation: Each step wraps `setTimeout` in a new Promise; chaining `.then` sequences the colors; the function recurses to restart the cycle.Write testLuck() that generates a random number and resolves with 'High chance to win <n>' if n > 0.7, otherwise rejects with 'Low chance to win <n>'. Log both branches.
Examples
Example 1:
Input: testLuck()
Output: 'High chance to win 0.831' or 'Low chance to win 0.475'
Explanation: One branch resolves, the other rejects; both are observed via `.then` / `.catch`.Rewrite the same flow with async/await and a try/catch. Compare the two styles in one or two sentences.
Examples
Example 1:
Input: await fetchData('/api/items')
Output: parsed JSON, or thrown error caught in catch
Explanation: `try/catch` brings synchronous control flow to async code; no nested `.then`/`.catch` chains.