Skip to content

Commit f1dc40b

Browse files
Update promises.md
1 parent a892720 commit f1dc40b

File tree

1 file changed

+171
-37
lines changed

1 file changed

+171
-37
lines changed

promises/promises.md

Lines changed: 171 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -198,63 +198,197 @@ fetch(githubUserInfoURL)
198198
- Each `.then()` returns a new promise, allowing you to chain further operations.
199199
- If any promise in the chain is rejected, control jumps to the nearest `.catch()`.
200200
- This pattern is useful for running async operations in sequence.
201-
202201
---
203202

204-
## Promise Methods
205-
### 1. Promise.resolve()
206-
Creates a promise that is resolved with a given value.
207-
```js
208-
Promise.resolve('Hello').then(console.log); // 'Hello'
203+
# Promise API
204+
205+
The `Promise` class provides 6 static methods for handling multiple promises efficiently.
206+
207+
## 1. Promise.all(promises)
208+
209+
**Purpose**: Execute promises in parallel, wait for ALL to complete
210+
**Behavior**: Resolves when all promises resolve, rejects if ANY promise rejects
211+
**Result**: Array of results in same order as input promises
212+
213+
`NOTE` : Please note that the order of the resulting array members is the same as in its source promises. Even though the first promise takes the longest time to resolve, it’s still first in the array of results.
214+
215+
```javascript
216+
Promise.all([
217+
new Promise(resolve => setTimeout(() => resolve(1), 3000)),
218+
new Promise(resolve => setTimeout(() => resolve(2), 2000)),
219+
new Promise(resolve => setTimeout(() => resolve(3), 1000))
220+
]).then(console.log); // [1, 2, 3] after 3 seconds
221+
222+
// Real-world example: Multiple API calls
223+
let urls = ['api/user1', 'api/user2', 'api/user3'];
224+
let requests = urls.map(url => fetch(url));
225+
Promise.all(requests).then(responses => {
226+
// All requests completed successfully
227+
});
209228
```
210229

211-
### 2. Promise.reject()
212-
Creates a promise that is rejected with a given reason.
213-
```js
214-
Promise.reject('Error!').catch(console.error); // 'Error!'
230+
**Key Points**:
231+
- Fails fast: if one rejects, entire operation fails
232+
- Non-promise values passed through as-is
233+
- Maintains order regardless of completion time
234+
- Other promises continue executing but results ignored on failure
235+
236+
## 2. Promise.allSettled(promises)
237+
238+
**Purpose**: Wait for ALL promises to complete, regardless of outcome
239+
**Behavior**: Never rejects, always waits for all promises to settle
240+
**Result**: Array of objects with `{status, value/reason}`
241+
242+
```javascript
243+
Promise.allSettled([
244+
fetch('https://api.github.com/users/validuser'),
245+
fetch('https://invalid-url'),
246+
Promise.resolve('direct value')
247+
]).then(results => {
248+
results.forEach((result, index) => {
249+
if (result.status === 'fulfilled') {
250+
console.log(`Success: ${result.value}`);
251+
} else {
252+
console.log(`Failed: ${result.reason}`);
253+
}
254+
});
255+
});
215256
```
216257

217-
### 3. Promise.all()
218-
Waits for all promises to resolve (or any to reject).
219-
```js
220-
const p1 = Promise.resolve(1);
221-
const p2 = Promise.resolve(2);
222-
Promise.all([p1, p2]).then(values => console.log(values)); // [1, 2]
258+
**Result Format**:
259+
- Success: `{status: "fulfilled", value: result}`
260+
- Failure: `{status: "rejected", reason: error}`
261+
262+
**Polyfill** (for older browsers):
263+
```javascript
264+
if (!Promise.allSettled) {
265+
Promise.allSettled = function(promises) {
266+
return Promise.all(promises.map(p =>
267+
Promise.resolve(p).then(
268+
value => ({status: 'fulfilled', value}),
269+
reason => ({status: 'rejected', reason})
270+
)
271+
));
272+
};
273+
}
223274
```
224275

225-
### 4. Promise.race()
226-
Resolves or rejects as soon as one of the promises does.
227-
```js
228-
const p1 = new Promise(res => setTimeout(() => res('First'), 100));
229-
const p2 = new Promise(res => setTimeout(() => res('Second'), 200));
230-
Promise.race([p1, p2]).then(console.log); // 'First'
276+
## 3. Promise.race(promises)
277+
278+
**Purpose**: Get result of the FIRST promise to settle (resolve OR reject)
279+
**Behavior**: Resolves/rejects with first settled promise
280+
**Result**: Single value from the fastest promise
281+
282+
```javascript
283+
Promise.race([
284+
new Promise(resolve => setTimeout(() => resolve('slow'), 3000)),
285+
new Promise(resolve => setTimeout(() => resolve('fast'), 1000)),
286+
new Promise((_, reject) => setTimeout(() => reject('error'), 2000))
287+
]).then(console.log); // 'fast' (after 1 second)
231288
```
232289

233-
### 5. Promise.allSettled()
234-
Waits for all promises to settle (resolve or reject).
235-
```js
236-
const p1 = Promise.resolve('Success');
237-
const p2 = Promise.reject('Fail');
238-
Promise.allSettled([p1, p2]).then(results => console.log(results));
290+
**Use Cases**:
291+
- Implementing timeouts
292+
- Getting fastest response from multiple sources
293+
- Circuit breaker patterns
294+
295+
## 4. Promise.any(promises)
296+
297+
**Purpose**: Get result of the FIRST promise to FULFILL (ignores rejections)
298+
**Behavior**: Resolves with first successful promise, rejects only if ALL fail
299+
**Result**: Single value from first successful promise, or AggregateError
300+
301+
```javascript
302+
Promise.any([
303+
new Promise((_, reject) => setTimeout(() => reject('Error 1'), 1000)),
304+
new Promise(resolve => setTimeout(() => resolve('Success!'), 2000)),
305+
new Promise(resolve => setTimeout(() => resolve('Also success'), 3000))
306+
]).then(console.log); // 'Success!' (after 2 seconds)
307+
308+
// All fail scenario
309+
Promise.any([
310+
Promise.reject('Error 1'),
311+
Promise.reject('Error 2')
312+
]).catch(error => {
313+
console.log(error.constructor.name); // AggregateError
314+
console.log(error.errors); // ['Error 1', 'Error 2']
315+
});
239316
```
240317

241-
---
318+
## 5. Promise.resolve(value)
242319

243-
## Error Handling
244-
Always use `.catch()` to handle errors in promise chains.
245-
```js
246-
fetch('invalid-url')
247-
.then(response => response.json())
248-
.catch(error => {
249-
console.error('Fetch failed:', error);
320+
**Purpose**: Create an immediately resolved promise
321+
**Use Case**: Ensure consistent promise interface
322+
323+
```javascript
324+
// These are equivalent
325+
Promise.resolve(42);
326+
new Promise(resolve => resolve(42));
327+
328+
// Practical example: Caching with consistent API
329+
let cache = new Map();
330+
function loadCached(url) {
331+
if (cache.has(url)) {
332+
return Promise.resolve(cache.get(url)); // Always return promise
333+
}
334+
return fetch(url).then(response => {
335+
cache.set(url, response);
336+
return response;
250337
});
338+
}
251339
```
252-
**Explanation:**
340+
341+
## 6. Promise.reject(error)
342+
343+
**Purpose**: Create an immediately rejected promise
344+
**Use Case**: Rarely used in practice (async/await preferred)
345+
346+
```javascript
347+
// These are equivalent
348+
Promise.reject(new Error('Failed'));
349+
new Promise((_, reject) => reject(new Error('Failed')));
350+
```
351+
352+
## Quick Comparison
353+
354+
| Method | Waits For | Resolves When | Rejects When |
355+
|--------|-----------|---------------|--------------|
356+
| `all` | All to settle | All resolve | Any rejects |
357+
| `allSettled` | All to settle | Always (never rejects) | Never |
358+
| `race` | First to settle | First resolves | First rejects |
359+
| `any` | First to fulfill | First resolves | All reject |
360+
361+
## Best Practices
362+
363+
1. **Use `Promise.all`** for parallel operations where you need all results
364+
2. **Use `Promise.allSettled`** when you want all results regardless of failures
365+
3. **Use `Promise.race`** for timeout implementations or fastest-wins scenarios
366+
4. **Use `Promise.any`** when you need the first successful result
367+
5. **`Promise.all` is most commonly used** in real applications
368+
6. **Consider error handling** - `Promise.all` fails fast, others have different behaviors
369+
370+
## Error Handling Patterns
371+
Always use `.catch()` to handle errors in promise chains.
253372
- If any error occurs in the chain, `.catch()` will handle it.
254373
- You can also use `.finally()` to run code regardless of success or failure.
374+
```javascript
375+
// Pattern 1: Fail fast with Promise.all
376+
Promise.all([api1(), api2(), api3()])
377+
.then(results => console.log('All succeeded:', results))
378+
.catch(error => console.log('At least one failed:', error));
379+
380+
// Pattern 2: Handle partial failures with Promise.allSettled
381+
Promise.allSettled([api1(), api2(), api3()])
382+
.then(results => {
383+
const successful = results.filter(r => r.status === 'fulfilled');
384+
const failed = results.filter(r => r.status === 'rejected');
385+
console.log(`${successful.length} succeeded, ${failed.length} failed`);
386+
});
387+
```
255388

256389
---
257390

391+
258392
## Async/Await (Promise Syntax Sugar)
259393
Async/await makes working with promises easier and more readable.
260394
```js

0 commit comments

Comments
 (0)