Skip to content

Commit ba70215

Browse files
authored
Added Promises content in introduction & about (#1397)
1 parent c7dfb39 commit ba70215

File tree

4 files changed

+337
-23
lines changed

4 files changed

+337
-23
lines changed

concepts/promises/about.md

Lines changed: 144 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,146 @@
11
# About
22

3-
TODO: add information on promises concept
3+
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
4+
5+
A Promise is in one of these states:
6+
7+
- **pending**: initial state, neither fulfilled nor rejected.
8+
- **fulfilled**: meaning that the operation was completed successfully and the result is available.
9+
- **rejected**: meaning that the operation failed.
10+
11+
When either of these options happens, the associated handlers queued up by a promise's `then` method is called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
12+
13+
Example:
14+
15+
```javascript
16+
const myPromise = new Promise(function (resolve, reject) {
17+
setTimeout(function (resolve, reject) {
18+
resolve('Jack');
19+
}, 300);
20+
});
21+
myPromise.then(function (e) {
22+
console.log(e); // expected output 'Jack'
23+
});
24+
```
25+
26+
## Instance Methods of a Promise
27+
28+
### then
29+
30+
> The `.then()` method takes up to two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining.[^1]
31+
32+
```javascript
33+
const promise1 = new Promise(function (resolve, reject) {
34+
resolve('Success!');
35+
});
36+
promise1.then(function (value) {
37+
console.log(value);
38+
// expected output: "Success!"
39+
});
40+
```
41+
42+
### catch
43+
44+
> A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is resolved. It is used to handle rejected promises.[^2]
45+
46+
```javascript
47+
const promise1 = new Promise((resolve, reject) => {
48+
throw 'An error occured';
49+
});
50+
promise1.catch(function (error) {
51+
console.error(error);
52+
});
53+
// expected output: An error occured
54+
```
55+
56+
### finally
57+
58+
> When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.[^3]
59+
60+
```javascript
61+
function findDataById(id) {
62+
return new Promise(function (resolve, reject) {
63+
let sampleData = [1, 2, 3, 4, 5];
64+
if (sampleData[id]) {
65+
resolve(sampleData[id]);
66+
} else {
67+
reject(new Error('Invalid id'));
68+
}
69+
});
70+
}
71+
findDataById(4)
72+
.then(function (response) {
73+
console.log(response);
74+
})
75+
.catch(function (err) {
76+
console.error(err);
77+
})
78+
.finally(function () {
79+
console.log('Promise completed');
80+
});
81+
```
82+
83+
## Static Methods of the Promise Class
84+
85+
Some of the [staic methods][promise-static-methods] that are available on `Promise` can be used resolve and reject promises. Here are a few of them:
86+
87+
### Promise.all
88+
89+
> The `Promise.all()` method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.[^4]
90+
91+
```javascript
92+
var p1 = Promise.resolve(10);
93+
var p2 = 45;
94+
var p3 = new Promise(function (resolve, reject) {
95+
setTimeout(function () {
96+
resolve('Jill');
97+
}, 300);
98+
});
99+
Promise.all([p1, p2, p3]).then(function (values) {
100+
console.log(values); // => [10, 45, "Jill"]
101+
});
102+
```
103+
104+
### Promise.reject
105+
106+
> The `Promise.reject()` method returns a Promise object that is rejected with a given reason.[^5]
107+
108+
```javascript
109+
Promise.reject(new Error('failed')).then(
110+
function () {
111+
// not called
112+
},
113+
function (error) {
114+
console.error(error); // error in the console
115+
}
116+
);
117+
```
118+
119+
### Promise.resolve
120+
121+
> The `Promise.resolve()` method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.[^6]
122+
123+
```javascript
124+
Promise.resolve('resolved!').then(
125+
function (value) {
126+
console.log(value); // "resolved!"
127+
},
128+
function (value) {
129+
// not called
130+
}
131+
);
132+
```
133+
134+
---
135+
136+
[^4]: `all`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
137+
[^5]: `reject`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject
138+
[^6]: `resolve`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
139+
[^1]: `then`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
140+
[^2]: `catch`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
141+
[^3]: `finally`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
142+
143+
[promise-catch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
144+
[promise-then]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
145+
[promise-finally]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
146+
[promise-static-methods]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#static_methods

concepts/promises/introduction.md

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,104 @@
11
# Introduction
22

3-
The `Promise` object represents the eventual completion (or failure) of an
3+
The [`Promise`][promise-docs] object represents the eventual completion (or failure) of an
44
asynchronous operation, and its resulting value.
5+
6+
The methods [`promise.then()`][promise-then], [`promise.catch()`][promise-catch], and [`promise.finally()`][promise-finally] are used to associate further action with a promise that becomes settled.
7+
8+
For example:
9+
10+
```javascript
11+
const myPromise = new Promise(function (resolve, reject) {
12+
let sampleData = [2, 4, 6, 8];
13+
let randomNumber = Math.ceil(Math.random() * 5);
14+
if (sampleData[randomNumber]) {
15+
resolve(sampleData[randomNumber]);
16+
} else {
17+
reject('An error occured!');
18+
}
19+
});
20+
21+
myPromise
22+
.then(function (e) {
23+
console.log(e);
24+
})
25+
.catch(function (error) {
26+
throw new Error(error);
27+
})
28+
.finally(function () {
29+
console.log('Promise completed');
30+
});
31+
```
32+
33+
## Methods
34+
35+
These methods are available on `Promise.prototype`
36+
37+
**then**
38+
39+
> The `.then()` method takes up to two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining.[^1]
40+
41+
```javascript
42+
const promise1 = new Promise(function (resolve, reject) {
43+
resolve('Success!');
44+
});
45+
46+
promise1.then(function (value) {
47+
console.log(value);
48+
// expected output: "Success!"
49+
});
50+
```
51+
52+
**catch**
53+
54+
> A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is resolved. It is used to handle rejected promises.[^2]
55+
56+
```javascript
57+
const promise1 = new Promise((resolve, reject) => {
58+
throw 'An error occured';
59+
});
60+
61+
promise1.catch(function (error) {
62+
console.error(error);
63+
});
64+
// expected output: An error occured
65+
```
66+
67+
**finally**
68+
69+
> When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.[^3]
70+
71+
```javascript
72+
function findDataById(id) {
73+
return new Promise(function (resolve, reject) {
74+
let sampleData = [1, 2, 3, 4, 5];
75+
if (sampleData[id]) {
76+
resolve(sampleData[id]);
77+
} else {
78+
reject(new Error('Invalid id'));
79+
}
80+
});
81+
}
82+
83+
findDataById(4)
84+
.then(function (response) {
85+
console.log(response);
86+
})
87+
.catch(function (err) {
88+
console.error(err);
89+
})
90+
.finally(function () {
91+
console.log('Promise completed');
92+
});
93+
```
94+
95+
---
96+
97+
[^1]: `then`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
98+
[^2]: `catch`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
99+
[^3]: `finally`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
100+
101+
[promise-docs]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
102+
[promise-catch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
103+
[promise-then]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
104+
[promise-finally]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

concepts/promises/links.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,9 @@
22
{
33
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises",
44
"description": "MDN: Using promises"
5+
},
6+
{
7+
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise",
8+
"description": "MDN: Introduction to Promises"
59
}
610
]
Lines changed: 88 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,104 @@
11
# Introduction
22

3-
The [`Promise` object][mdn-promise] represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
3+
The [`Promise`][promise-docs] object represents the eventual completion (or failure) of an
4+
asynchronous operation, and its resulting value.
45

5-
> Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
6+
The methods [`promise.then()`][promise-then], [`promise.catch()`][promise-catch], and [`promise.finally()`][promise-finally] are used to associate further action with a promise that becomes settled.
67

7-
A `Promise` has three states:
8+
For example:
89

9-
1. unresolved
10-
2. resolved
11-
3. rejected
10+
```javascript
11+
const myPromise = new Promise(function (resolve, reject) {
12+
let sampleData = [2, 4, 6, 8];
13+
let randomNumber = Math.ceil(Math.random() * 5);
14+
if (sampleData[randomNumber]) {
15+
resolve(sampleData[randomNumber]);
16+
} else {
17+
reject('An error occured!');
18+
}
19+
});
1220

13-
When a `Promise` is _settled_, it means that it has either _resolved_ or _rejected_.
21+
myPromise
22+
.then(function (e) {
23+
console.log(e);
24+
})
25+
.catch(function (error) {
26+
throw new Error(error);
27+
})
28+
.finally(function () {
29+
console.log('Promise completed');
30+
});
31+
```
1432

15-
## Guarantees
33+
## Methods
1634

17-
Unlike old-fashioned _passed-in_ callbacks, a promise comes with some guarantees, including, but not limited to:
35+
These methods are available on `Promise.prototype`
1836

19-
- A `Promise` can only change its state _once_, which means that a resolved promise can never become rejected.
20-
- Callbacks added with [`.then`][mdn-promise-then] are called even if the promise has already settled.
21-
- Multiple callback may be added using [`.then`][mdn-promise-then], and those callbacks will be invoked in the order as they were inserted.
37+
**then**
2238

23-
## Chaining
39+
> The `.then()` method takes up to two arguments; the first argument is a callback function for the resolved case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining.[^1]
2440
25-
> TODO: `.then`, `.catch`
41+
```javascript
42+
const promise1 = new Promise(function (resolve, reject) {
43+
resolve('Success!');
44+
});
2645

27-
## Constructing
46+
promise1.then(function (value) {
47+
console.log(value);
48+
// expected output: "Success!"
49+
});
50+
```
2851

29-
> TODO: `Promise.resolve` `Promise.reject` `new Promise(resolve, reject)`
52+
**catch**
3053

31-
## More about promises
54+
> A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is resolved. It is used to handle rejected promises.[^2]
3255
33-
See [this guide][mdn-guide-promise] for more about using promises.
56+
```javascript
57+
const promise1 = new Promise((resolve, reject) => {
58+
throw 'An error occured';
59+
});
3460

35-
[mdn-promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
36-
[mdn-promise-then]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
37-
[mdn-guide-promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
61+
promise1.catch(function (error) {
62+
console.error(error);
63+
});
64+
// expected output: An error occured
65+
```
66+
67+
**finally**
68+
69+
> When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.[^3]
70+
71+
```javascript
72+
function findDataById(id) {
73+
return new Promise(function (resolve, reject) {
74+
let sampleData = [1, 2, 3, 4, 5];
75+
if (sampleData[id]) {
76+
resolve(sampleData[id]);
77+
} else {
78+
reject(new Error('Invalid id'));
79+
}
80+
});
81+
}
82+
83+
findDataById(4)
84+
.then(function (response) {
85+
console.log(response);
86+
})
87+
.catch(function (err) {
88+
console.error(err);
89+
})
90+
.finally(function () {
91+
console.log('Promise completed');
92+
});
93+
```
94+
95+
---
96+
97+
[^1]: `then`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
98+
[^2]: `catch`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
99+
[^3]: `finally`, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
100+
101+
[promise-docs]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
102+
[promise-catch]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
103+
[promise-then]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
104+
[promise-finally]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

0 commit comments

Comments
 (0)