Skip to content

Commit c48633d

Browse files
Patrick SmithPatrick Smith
authored andcommitted
Write about promises
1 parent 6e101c1 commit c48633d

File tree

1 file changed

+45
-1
lines changed
  • apps/components_guide_web/lib/components_guide_web/templates/web_standards

1 file changed

+45
-1
lines changed
Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
11
# Promise
22

3-
You can think of a Promise as a value. Once a Promise has been created, you can’t changed the value. Sooner or later its value will be given — as promised. Or it may fail with an error.
3+
You can think of a Promise as a value. Once a Promise has been created, you can’t changed the value. Sooner or later its value will be given — as promised. (Or it may fail with an error. More on that later.)
4+
5+
## Promises are eager
6+
7+
Let's compare two code samples.
8+
9+
```js
10+
const promisedValue = new Promise((resolve, reject) => {
11+
console.log("Creating value");
12+
resolve(40 + 2);
13+
});
14+
```
15+
16+
How many times will we see _Creating value_ logged?
17+
18+
```js
19+
const promisedValue = new Promise((resolve, reject) => {
20+
console.log("Creating value");
21+
resolve(40 + 2);
22+
});
23+
24+
promisedValue.then(console.log);
25+
promisedValue.then(console.log);
26+
promisedValue.then(console.log);
27+
```
28+
29+
How many times will we see _Creating value_ logged?
30+
31+
We will see it logged only once, because promises are created eagerly. Listening to a promise using `.then()` does not affect nor start the source promise.
32+
33+
Once a promise has been created, then you may wait to hear its result zero times, one time, or fifteen times, and the original promise will behave the same.
34+
35+
If we have a value in a variable, we feel comfortable knowing that the reading of that variable has no effect on its value.
36+
37+
```js
38+
const value = 40 + 2;
39+
40+
console.log(value);
41+
console.log(value);
42+
console.log(value);
43+
```
44+
45+
42 will be logged three times, but if removed the logs altogether, the value will remain the same. The act of logging had no effect on the source value. Promises work exactly the same.
46+
47+
We can use this to our advantage, by thinking about promises in the same way we think about values.

0 commit comments

Comments
 (0)