~/
hackweb.dev
JavaScript Promises Deep Dive
Quiz
⌘K
...
~/
/tutorials
/js/js-promises-deep-dive/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/29js-promises-deep-dive
Write
Preview
Diff
# JavaScript Promises Deep Dive Master asynchronous programming with promises. ## Promise Basics ```javascript let promise = new Promise((resolve, reject) => { let success = true; if (success) resolve("Done!"); else reject(new Error("Failed!")); }); promise .then(result => console.log(result)) .catch(error => console.error(error.message)); ``` ## Promise States Three states: `pending` → `fulfilled` or `rejected`. Once settled, never changes. ```javascript let p = new Promise((resolve) => { setTimeout(() => resolve("Done"), 1000); }); ``` ## Promise Chaining Return values from `.then()` pass to the next `.then()`. ```javascript fetchUser() .then(user => fetchPosts(user.id)) .then(posts => console.log(posts)) .catch(error => console.error(error.message)); ``` **Tip:** A single `.catch()` at the end handles errors from any step. ## Promise.all() Run multiple promises in parallel. Fails fast if any rejects. ```javascript Promise.all([fetch("/api/users"), fetch("/api/posts")]) .then(([users, posts]) => console.log(users, posts)) .catch(error => console.error("One failed:", error.message)); ``` ## Promise.allSettled() Wait for all, regardless of success or failure. ```javascript Promise.allSettled([p1, p2, p3]).then(results => { results.forEach(r => console.log(r.status, r.value || r.reason)); }); ``` ## Promise.race() and Promise.any() `race()` — first to settle wins. `any()` — first to fulfill wins (ignores rejections). ```javascript Promise.race([fast, slow]).then(result => console.log(result)); Promise.any([p1, p2, p3]).then(result => console.log(result)); ``` ## Data Fetcher Example ```javascript class DataFetcher { #baseUrl; constructor(baseUrl) { this.#baseUrl = baseUrl; } get(endpoint) { return fetch(`${this.#baseUrl}${endpoint}`) .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }); } fetchAll(endpoints) { return Promise.all(endpoints.map(e => this.get(e))); } } ``` ## File Processing Pipeline ```javascript readFile("input.txt") .then(data => processFile(data)) .then(processed => saveFile("output.txt", processed)) .then(result => console.log(result)) .catch(error => console.error(error)); ``` ## Best Practices - **Always handle errors** — Use `.catch()` or try/catch - **Chain promises** — Avoid nested `.then()` - **Use `Promise.all()`** — For parallel operations - **Use `finally`** — For cleanup that always runs ## Common Mistakes - **Forgetting `return` in `.then()`** — Returns undefined - **Not handling errors** — Unhandled rejections - **Nested promises** — Hard to read - **Ignoring rejections** — Silent failures
No changes yet
Reset to original
Submit suggestion
cancel