You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Any how many times will we see _Creating value_ logged here?
30
-
31
-
In both cases, we will see it logged only once, because promises are created eagerly.
27
+
In both cases, we will see it logged only once. This is because promises are run once are created eagerly.
32
28
33
-
Listening to a promise using `.then()` does not affect nor start that promise.
29
+
Listening to a promise using `.then()` does not affect nor start that promise. It has no side-effects on the source promise.
34
30
35
31
Once a promise has been created, then you may wait to hear its result one time, fifteen times, or not at all, and the original promise will behave the same.
36
32
37
33
This may seem like a strange limitation, but it simplifies reasoning about promises as they work similar to _values_.
38
34
39
35
### How values work
40
36
41
-
If we store a value in a variable, we feel comfortable knowing that the reading of that variable has absolutely no effect on its value.
37
+
If we store a value in a variable, we can feel comfortable knowing that the reading of that variable has absolutely no effect on its underlying value.
42
38
43
39
```js
44
40
constvalue=40+2;
@@ -48,8 +44,142 @@ console.log(value);
48
44
console.log(value);
49
45
```
50
46
51
-
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.
47
+
The value of `42` will be logged three times, but if the logs were removed altogether, the variable’s value won’t be affected and will remain the same. The act of logging had no effect on the source value.
52
48
53
49
Promises work exactly the same.
54
50
55
51
We can use this to our advantage, by thinking about promises in the same way we think about values.
52
+
53
+
### Reusing
54
+
55
+
If data is loaded from an API, we might use `fetch()`.
console.log('decoding data'); // How many times will we see this logged?
73
+
returnresponse.json();
74
+
});
75
+
76
+
promisedData.then(data=> {
77
+
// Use data
78
+
});
79
+
80
+
promisedData.then(data=> {
81
+
// Use data again
82
+
});
83
+
```
84
+
85
+
Here will see `decoding data` logged once. The `fetch()` call returns a Promise, which is chained using `.then()` to unwrap the underlying JSON body by calling `.json()` on the response.
86
+
87
+
We can continue to think of these as eventual values. Once these values have been cast, they cannot change (technically we could mutate anything as JavaScript gives us free reign but we shouldn’t).
88
+
89
+
The response from `fetch()` is one eventual value. The decode JSON is another eventual value, and actually has two Promises, one created by the `.json()` method, and another wrapping that created by `.then()`.
0 commit comments