Promises
27 bites tagged Promises — interview questions with model answers, and 60-second explainers.
Promise .catch() versus async/await try...catch
.catch() handles rejection for all preceding chain steps and reads functionally; try/catch reads synchronously and can scope errors per await, but only catches awaited rejections. Async error-handling models.
Callback hell and how to refactor it
Deeply nested callbacks (pyramid of doom) hurt readability and error handling, refactor with promises or async/await. managing async control flow readably.
Microtask versus macrotask execution order in Node
NextTick drains before promises, both microtask queues flush fully between each macrotask, timers and setImmediate are macrotasks. precise grasp of event loop ordering.
Testing async Promise-returning code in Jest
Return or await the promise; use await expect(...).resolves/rejects, or await the value directly. Whether you make async assertions actually run before the test ends.
Propagating async errors to Express error handlers
Express does not auto-catch rejected promises, so catch and call next(err), or wrap handlers in an asyncHandler that forwards rejections; Express 5 awaits handlers automatically. async error forwarding.
Promise.all vs Promise.allSettled
All rejects on the first failure; allSettled always fulfills with a status/value or reason per input. Use allSettled when partial success is acceptable. choosing fail-fast vs collect-all.
Comparing the three async error-handling styles
Callbacks pass err as first arg; Promises route errors to catch; async/await uses try/catch; an unhandled rejection can crash the Node process. fluency across async error styles.
Running independent requests with Promise.all and race
Start all requests then await Promise.all to get all results or fail fast on first rejection; use Promise.race when only the fastest settled result matters. concurrent Promise combinators.
The three states of a JavaScript Promise
Pending, fulfilled, rejected; settle is one-way and final; create with the executor calling resolve or reject, consume with then and catch. fundamentals of Promise lifecycle.
Write a generic fetchJSON<T> wrapper and explain its type safety benefits
Tests preserving type info across async boundaries via generics. Outline: write fetchJSON<T> returning Promise<T>, note response.json() is any, and show T lets callers lock in the response shape for compile-time checks.
Write a typed async fetchUser with error handling
Tests promise-based fetch plus TypeScript return-type contracts. A strong answer checks response.ok before response.json() and types the return as Promise<User>. A red flag is swallowing 4xx/5xx errors silently.
How would you modify fetch to handle HTTP error statuses?
Verify response.ok in then and throw if false, then catch network failures separately. awareness that fetch resolves on HTTP errors and needs manual status checking.
Implement inSequence(tasks) to execute promise-returning functions sequentially
Tests async/await control flow versus Promise.all parallelism. A strong answer uses a for-of loop with await inside an async function, accumulates results in order, and stops cleanly on rejection. Red flag: suggesting Promise.all or forEach with await.
How do you type an async function return in TypeScript?
This tests if you know async functions always return Promise<T>. A great answer: annotate Promise<User>, return User from the body, and note TypeScript implicitly wraps it. A red flag is omitting Promise and typing the return as just User.
How do you wrap a callback-based API into a Promise?
This tests Promise constructor mechanics and callback migration. A strong answer returns a new Promise, calls the legacy function, maps success to resolve and errors to reject.
Returning Promises from React Native Modules
A native module promise is an IOU across the bridge: JS asks native for a future result. Use them when native work like file encryption must run off the JS thread. If native code never resolves the promise, the JS await hangs forever and leaks.
Promise Cleanup with .finally()
Promise.finally() is the `try...catch...finally` for async code, guaranteeing logic runs after a promise settles. Use it to hide a loading spinner or close a network connection without duplicating code in `.then()` and `.catch()`.
Axios: A Simpler Way to Make HTTP Requests
Axios simplifies making network requests by wrapping native browser APIs in a promise-based client. Use it to GET or POST data in any JavaScript app. The main footgun is forgetting requests are asynchronous; you must use `async/await` to get the data.
Promise.any(): Get the Fastest Successful Result
Promise.any() is a race where only finishers count. It returns the value of the first promise to succeed, ignoring any that fail. Use it to query redundant endpoints and take the first successful response.
Promise.allSettled(): Never Fail a Batch of Promises
Promise.allSettled() waits for every promise in a set to finish, success or fail, without short-circuiting. Use it for independent tasks, like multiple API calls, where you need the outcome of each.
Promise.race(): First Promise to Settle Wins
Promise.race() returns a promise that mirrors the outcome of the first promise in a set to finish—the winner takes all, whether it resolves or rejects. Use it to set a timeout on a network request.
Promise.all(): Wait for Multiple Promises at Once
Promise.all() runs multiple promises in parallel, resolving only when all have succeeded. It's for when you need data from several API endpoints to render a single component.
Async/Await: Write Non-Blocking Code That Reads Synchronously
async/await lets you write non-blocking code that reads like simple, synchronous logic. It's used for network requests or database queries without freezing your app. The biggest footgun is using `await` inside a function you forgot to declare as `async`.
Node.js util.promisify: From Callbacks to Promises
util.promisify converts callback-based functions into Promise-based ones, letting you use async/await with older Node.js APIs. It's a bridge for legacy code following the standard (err, value) callback pattern. The footgun: it fails on non-standard signatures.
Get Promises bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.