Async
92 bites tagged Async — interview questions with model answers, and 60-second explainers.
Make a GET request with http and parse JSON in Dart
Practical Dart async networking with package:http and dart:convert. Import http, await get(Uri.parse(url)), verify statusCode is 200, then jsonDecode(response.body) as List<Map<String, dynamic>>. Skipping status checks or decoding without a cast.
How do you pass data with Navigator.push and return data with Navigator.pop?
Tests imperative navigation and async result patterns. Strong answer: push via MaterialPageRoute with constructor args; await the Future from Navigator.push; pop with Navigator.pop(context, result). Red flag: using global state instead of the Future result.
Explain StreamController, write a broadcast stream example, and why close it?
This tests Dart stream lifecycle and memory safety. A strong answer uses StreamController.broadcast(), adds data and errors, closes it, and explains unclosed controllers leak memory.
Fetch user profiles concurrently and handle individual failures
Tests Future.wait concurrency and per-future error isolation. Answer: map IDs to fetchProfile, pass to Future.wait. For partial failures, attach catchError per future to return null, then filter. Red flag: try-catch around Future.wait or sequential awaits.
Explain single-subscription vs broadcast Streams in Dart
Tests dart:async stream lifecycle. Outline: single-subscription allows one listener and emits on listen; broadcast supports many but drops events for late arrivals. Red flag: saying single-subscription allows multiple listeners or buffers events.
Difference between Future<void> and void from an async function
Future<void> lets callers await and catch errors; void hides the Future, preventing await and leaving exceptions uncaught. Knowledge that async always produces a Future. Believing void async returns are awaitable.
Define a Dart Future, return Future<String>, and handle errors with both patterns.
Tests Dart async primitives and error handling. A strong answer defines Future as a pending async result, writes a delayed Future<String>, consumes it with then/catchError, and mirrors with async/await try/catch.
Explain Dart's event loop, microtask queue, event queue, and await behavior
Tests Dart single-threaded event loop model. Strong answer: microtasks drain before event queue tasks; await suspends the function and schedules its resumption via the event loop when the Future completes. Red flag: claiming await blocks the thread.
AbortController: Cancel In-Flight Web Requests
AbortController is a remote kill switch for web requests. You create a controller, pass its `signal` to a `fetch` call, and can then call `abort()` to cancel it. Use it to stop requests when a user navigates away. The footgun is forgetting this signal.
Fetch API: Making Basic Network Requests
The Fetch API is like ordering from a catalog: you give it a URL and get a promise of delivery. It's used to load data from APIs without a page reload. The footgun: the promise resolves even on HTTP errors (like 404); you must check.
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()`.
The Promise Constructor: Wrapping Old Callbacks
The `Promise` constructor turns old callback-style functions into modern promises you can `await`. Use it to "promisify" APIs like `setTimeout` that don't return promises. The footgun is wrapping already-promise-based code, creating unnecessary complexity.
The JavaScript Event Loop: Asynchronicity on a Single Thread
The event loop is a queue that lets single-threaded JavaScript handle asynchronous tasks without blocking. It processes callbacks from Web APIs like `fetch` or `setTimeout` one at a time. The footgun: `setTimeout(fn, 0)` doesn't run instantly, just next.
Handling Asynchronous UI with Testing Library
Your test shouldn't race your UI. Use async helpers to wait for elements to appear, disappear, or change after an event. This is crucial for testing components that fetch data. The footgun is forgetting `await` on `findBy` or `waitFor` calls.
AbortController: Stop Fetch Requests You No Longer Need
An AbortController is a kill switch for network requests. Use it to cancel a `fetch` when a user navigates away. The main footgun is not handling the `AbortError` that `fetch` throws, which can look like a real network failure.
Redux Saga: Managing Side Effects with Generators
Redux Saga runs side effects in a separate thread-like process. It listens for Redux actions and executes complex async tasks, like API calls, keeping that logic out of your components.
FastAPI Background Tasks: Don't Make the Client Wait
FastAPI background tasks let you run slow operations, like sending an email, *after* returning a response. This keeps your API fast. The main footgun: these are fire-and-forget; a server crash means the task is lost without a real message queue.
Node.js File I/O: Synchronous vs. Asynchronous
Synchronous file I/O blocks your app, like waiting at a counter for your order. Asynchronous I/O gets a buzzer, letting your app work on other tasks. Use async for servers and sync for simple, one-off scripts. The footgun is using sync I/O in a server.
Top-Level Await: `await` Without an `async` Function
Top-level await lets you use `await` directly in an ES module, no `async` function needed. Use it to initialize resources like database connections on startup. The footgun: the entire module's execution blocks until the promise resolves, delaying startup.
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.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.
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.
Promise.then(): Each Call Returns a New Promise
Each `.then()` call returns a new promise, letting you chain async tasks sequentially. This is key for multi-step operations like API calls. The footgun is attaching multiple `.then()`s to the original promise, which executes them in parallel, not in sequence.
Get Async bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.