Promises and async/await are JavaScript's tools for working with asynchronous operations such as API calls, timers and file reads, without blocking the main thread. Promises A Promise represents a value that will be available in the future. It is in one of three states: - pending: the operation has not completed yet, - fulfilled: it succeeded with a value, - rejected: it failed with a reason (usually an Error). Once fulfilled or rejected, a promise is settled and never changes state. Creating and consuming a promise function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } fetch('/api/users/42') .then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }) .then(user => console.log(user.name)) .catch(error => console.error('Failed:', error)) .finally(() => console.log('Done')); Each then returns a new promise, enabling chaining. Errors propagate down the chain to the nearest catch. async/await Syntactic sugar over promises (ES2017) that makes asynchronous code read like synchronous code. - An async function always returns a promise. - await pauses the function until the promise settles, then returns its value or throws its error. async function loadUser(id) { try { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error(`HTTP ${response.status}`); const user = await response.json(); return user; } catch (error) { console.error('Could not load user', error); throw error; } finally { console.log('Request finished'); } } await only pauses the current async function; the rest of the program keeps running, and the continuation is scheduled as a microtask when the promise settles. Running promises concurrently Sequential (slower when operations are independent): const user = await getUser(); const orders = await getOrders(); Parallel: const [user, orders] = await Promise.all([getUser(), getOrders()]); Promise combinators - Promise.all: waits for all; rejects as soon as one rejects. - Promise.allSettled: waits for all and returns each result's status (useful when partial failures are acceptable). - Promise.race: settles with the first promise to settle (useful for timeouts). - Promise.any: fulfils with the first fulfilled promise; rejects only if all reject. Cancellation Promises cannot be cancelled by themselves. Use AbortController with fetch and other APIs that support signals: const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort(); Common mistakes - Forgetting await, so you work with a pending promise instead of the value. - Using await inside loops for independent operations (slow); use Promise.all, or limit concurrency for large batches. - Unhandled rejections: always catch errors (try/catch with await, or .catch()); unhandled rejections can crash Node.js processes. - Using async callbacks with forEach, which does not wait for them; use for...of with await or Promise.all with map. - Mixing callbacks and promises inconsistently. Interview summary: "A Promise represents a future result with pending, fulfilled or rejected states, consumed with then and catch. async/await builds on promises to write asynchronous code in a synchronous style with try/catch. Use Promise.all and related combinators for concurrency and AbortController for cancellation."
Ravindra Wadile · · 0 likes