Async
92 bites tagged Async — interview questions with model answers, and 60-second explainers.
How do you cancel pending fetches using AbortController?
Keep one AbortController, abort before each fetch, pass its signal, and swallow AbortError. Async cancellation and race-condition prevention in UI streams. Forgetting prior abort or leaving rejections uncaught.
How do you fetch from three APIs using Promise.all versus allSettled?
Promise.all parallelizes but rejects on first failure. allSettled returns every outcome with status, value, and reason. Promise concurrency and failure isolation. Wrapping each call in try-catch to imitate allSettled.
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.
How would you handle an async API call in Redux Toolkit versus Zustand?
Tests structured async state machines versus lightweight patterns. A strong answer contrasts createAsyncThunk's pending/fulfilled/rejected lifecycles with Zustand's direct set() in async functions, noting Redux's traceability trade-off.
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.
How do you inspect WebSocket close codes in FastAPI?
Tests WebSocket lifecycle handling in FastAPI. Strong answers catch the disconnect exception, read its code attribute, and log 1000 for normal closures versus 1001/1006 for crashes.
How do you define a WebSocket endpoint in FastAPI?
Import WebSocket, use @app.websocket, await accept, receive_text, then send_text. async endpoint wiring and the accept-receive-send lifecycle. forgetting accept or treating it like a standard HTTP route.
How do you test a FastAPI WebSocket endpoint and lifecycle with pytest?
Tests knowledge of FastAPI TestClient usage for async WebSocket lifecycles. Use a with statement for websocket_connect; assert send, receive_json, and close; tests use standard def because TestClient handles the async app.
Purpose of await next(request) in FastAPI middleware and timing effects
Tests ASGI middleware lifecycle. await next(request) forwards the request downstream to the endpoint and returns the response. Pre-call code touches the request; post-call code touches the response.
How do you send an email without blocking a FastAPI request?
Tests knowledge of FastAPI's BackgroundTasks for post-response work. Strong answer: import it, inject into the endpoint, define a task function, and call add_task before returning. Recommending raw asyncio.create_task or insisting Celery is required.
How does FastAPI execute setup and teardown in nested yield dependencies?
It tests FastAPI's dependency injection lifecycle and stack-like teardown for nested yield dependencies. Setup runs top-down; teardown runs bottom-up after the response. A red flag is claiming teardown order is arbitrary or follows garbage collection.
Access raw request bytes in FastAPI for webhook verification
Tests FastAPI's Starlette integration and stream semantics. Outline: inject Request and await request.body, but the stream is single-use so JSON parsing later fails and docs are lost. Red flag: suggesting a Pydantic model still works after consuming the body.
How would you use BackgroundTasks to run work after returning a 201?
What it tests: FastAPI deferred execution and failure modes. A strong answer injects BackgroundTasks, adds the task, returns 201, and notes same-process post-response execution with no persistence. Red flag: Treating it as a distributed queue like Celery.
Implement an async database session dependency using yield for setup and teardown
This tests async resource lifecycle management in FastAPI. A strong answer uses async def, yields a session inside try, closes in finally, and injects with Depends. A red flag is omitting finally or using sync def for async I/O, which leaks connections.
Write an async decorator that logs execution time for FastAPI
Use functools.wraps, wrap perf_counter around awaited call, log ms, and place decorator above path operation. Python closures, async/await, and decorator stacking in FastAPI. forgetting to await the coroutine or omitting wraps.
What is the difference between def and async def in Python and FastAPI?
Tests event-loop boundaries: async def yields control via await for non-blocking I/O, def runs in a threadpool. Use async def only with async libraries; def covers blocking calls. Red flag: claiming async is automatically faster or awaiting inside def.
Async Path Operations in FastAPI
FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.
Python Async Context Managers
Async context managers let you await during setup and teardown. Use async with for database connections or streams where acquiring and releasing both need I/O. The footgun is applying @contextmanager to async cleanup, which cannot await and will crash.
Go select vs Rust select! fairness and determinism
This tests runtime fairness in concurrent primitives. Contrast Go's pseudo-random case selection with Tokio's randomized default and its opt-in biased; top-down mode. Red flag: claiming Go uses source order or that Rust randomization is unavoidable.
What is a Dart Completer and when should you use it?
This tests bridging callback APIs into Dart's Future ecosystem. An answer defines Completer as a manual Future producer, explains completing with value or error from callbacks, preferring Future() when possible. A red flag is using Completer for simple async.
How do you diagnose and fix flaky Flutter widget tests?
Audit unawaited futures, swap pumpAndSettle for explicit pumps or mock timers, and reproduce with logs. Deterministic control of Flutter async and animation timing. Retries or sleeps instead of removing timing leaks.
Why is Flutter local storage async and how do you use shared_preferences?
Tests why disk I/O must avoid blocking Dart's UI thread. A strong answer shows async/await with getInstance and setters, notes legacy getters are sync-after-cache, and warns writes may not persist instantly.
Why are stale search requests problematic and how do you cancel them?
This tests race conditions and resource waste in async UI. Strong answers note stale requests waste bandwidth and overwrite newer results; cancel the previous call with a CancelToken before issuing the next.
Explain FutureBuilder and how it manages async UI states
This tests declarative async UI state management. Obtain the Future before build, pass it to FutureBuilder, and branch on snapshot.connectionState and hasError to render loading, data, or error states.
Get Async bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.