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
Copy file name to clipboardExpand all lines: 1-js/11-async/03-promise-chaining/01-then-vs-catch/solution.md
+2-2Lines changed: 2 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
The short answer is: **no, they are not the equal**:
1
+
The short answer is: **no, they are not equal**:
2
2
3
3
The difference is that if an error happens in `f1`, then it is handled by `.catch` here:
4
4
@@ -17,4 +17,4 @@ promise
17
17
18
18
That's because an error is passed down the chain, and in the second code piece there's no chain below `f1`.
19
19
20
-
In other words, `.then` passes results/errors to the next `.then/catch`. So in the first example, there's a `catch` below, and in the second one -- there isn't, so the error is unhandled.
20
+
In other words, `.then` passes results/errors to the next `.then/catch`. So in the first example, there's a `catch` below, and in the second one there isn't, so the error is unhandled.
Copy file name to clipboardExpand all lines: 1-js/11-async/03-promise-chaining/article.md
+27-47Lines changed: 27 additions & 47 deletions
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
1
1
2
2
# Promises chaining
3
3
4
-
Let's return to the problem mentioned in the chapter <info:callbacks>: we have a sequence of asynchronous tasks to be done one after another. For instance, loading scripts. How can we code it well?
4
+
Let's return to the problem mentioned in the chapter <info:callbacks>: we have a sequence of asynchronous tasks to be performed one after another — for instance, loading scripts. How can we code it well?
5
5
6
6
Promises provide a couple of recipes to do that.
7
7
@@ -48,24 +48,6 @@ The whole thing works, because a call to `promise.then` returns a promise, so th
48
48
49
49
When a handler returns a value, it becomes the result of that promise, so the next `.then` is called with it.
50
50
51
-
To make these words more clear, here's the start of the chain:
52
-
53
-
```js run
54
-
newPromise(function(resolve, reject) {
55
-
56
-
setTimeout(() =>resolve(1), 1000);
57
-
58
-
}).then(function(result) {
59
-
60
-
alert(result);
61
-
return result *2; // <-- (1)
62
-
63
-
}) // <-- (2)
64
-
// .then…
65
-
```
66
-
67
-
The value returned by `.then` is a promise, that's why we are able to add another `.then` at `(2)`. When the value is returned in `(1)`, that promise becomes resolved, so the next handler runs with the value.
68
-
69
51
**A classic newbie error: technically we can also add many `.then` to a single promise. This is not chaining.**
70
52
71
53
For example:
@@ -90,7 +72,7 @@ promise.then(function(result) {
90
72
});
91
73
```
92
74
93
-
What we did here is just several handlers to one promise. They don't pass the result to each other, instead they process it independently.
75
+
What we did here is just several handlers to one promise. They don't pass the result to each other; instead they process it independently.
94
76
95
77
Here's the picture (compare it with the chaining above):
96
78
@@ -102,9 +84,9 @@ In practice we rarely need multiple handlers for one promise. Chaining is used m
102
84
103
85
## Returning promises
104
86
105
-
Normally, a value returned by a `.then` handler is immediately passed to the next handler. But there's an exception.
87
+
A handler, used in `.then(handler)` may create and return a promise.
106
88
107
-
If the returned value is a promise, then the further execution is suspended until it settles. After that, the result of that promise is given to the next `.then` handler.
89
+
In that case further handlers wait until it settles, and then get its result.
108
90
109
91
For instance:
110
92
@@ -138,15 +120,15 @@ new Promise(function(resolve, reject) {
138
120
});
139
121
```
140
122
141
-
Here the first `.then` shows `1` returns `new Promise(…)` in the line `(*)`. After one second it resolves, and the result (the argument of `resolve`, here it's `result*2`) is passed on to handler of the second `.then`in the line `(**)`. It shows `2` and does the same thing.
123
+
Here the first `.then` shows `1`and returns `new Promise(…)` in the line `(*)`. After one second it resolves, and the result (the argument of `resolve`, here it's `result * 2`) is passed on to handler of the second `.then`. That handler is in the line `(**)`, it shows `2` and does the same thing.
142
124
143
-
So the output is again 1 -> 2 -> 4, but now with 1 second delay between `alert` calls.
125
+
So the output is the same as in the previous example: 1 -> 2 -> 4, but now with 1 second delay between `alert` calls.
144
126
145
127
Returning promises allows us to build chains of asynchronous actions.
146
128
147
129
## Example: loadScript
148
130
149
-
Let's use this feature with `loadScript` to load scripts one by one, in sequence:
131
+
Let's use this feature with the promisified `loadScript`, defined in the [previous chapter](info:promise-basics#loadscript), to load scripts one by one, in sequence:
Here each `loadScript` call returns a promise, and the next `.then` runs when it resolves. Then it initiates the loading of the next script. So scripts are loaded one after another.
184
166
185
-
We can add more asynchronous actions to the chain. Please note that code is still "flat", it grows down, not to the right. There are no signs of "pyramid of doom".
167
+
We can add more asynchronous actions to the chain. Please note that the code is still "flat" — it grows down, not to the right. There are no signs of the "pyramid of doom".
186
168
187
-
Please note that technically we can add `.then` directly to each `loadScript`, like this:
169
+
Technically, we could add `.then` directly to each `loadScript`, like this:
@@ -207,11 +189,9 @@ Sometimes it's ok to write `.then` directly, because the nested function has acc
207
189
208
190
209
191
````smart header="Thenables"
210
-
To be precise, `.then` may return an arbitrary "thenable" object, and it will be treated the same way as a promise.
211
-
212
-
A "thenable" object is any object with a method `.then`.
192
+
To be precise, a handler may return not exactly a promise, but a so-called "thenable" object - an arbitrary object that has a method `.then`. It will be treated the same way as a promise.
213
193
214
-
The idea is that 3rd-party libraries may implement "promise-compatible" objects of their own. They can have extended set of methods, but also be compatible with native promises, because they implement `.then`.
194
+
The idea is that 3rd-party libraries may implement "promise-compatible" objects of their own. They can have an extended set of methods, but also be compatible with native promises, because they implement `.then`.
215
195
216
196
Here's an example of a thenable object:
217
197
@@ -229,30 +209,32 @@ class Thenable {
229
209
230
210
new Promise(resolve => resolve(1))
231
211
.then(result => {
212
+
*!*
232
213
return new Thenable(result); // (*)
214
+
*/!*
233
215
})
234
216
.then(alert); // shows 2 after 1000ms
235
217
```
236
218
237
-
JavaScript checks the object returned by `.then` handler in the line `(*)`: if it has a callable method named `then`, then it calls that method providing native functions `resolve`, `reject` as arguments (similar to executor) and waits until one of them is called. In the example above `resolve(2)` is called after 1 second `(**)`. Then the result is passed further down the chain.
219
+
JavaScript checks the object returned by the `.then` handler in line `(*)`: if it has a callable method named `then`, then it calls that method providing native functions `resolve`, `reject` as arguments (similar to an executor) and waits until one of them is called. In the example above `resolve(2)` is called after 1 second `(**)`. Then the result is passed further down the chain.
238
220
239
-
This feature allows to integrate custom objects with promise chains without having to inherit from `Promise`.
221
+
This feature allows us to integrate custom objects with promise chains without having to inherit from `Promise`.
240
222
````
241
223
242
224
243
225
## Bigger example: fetch
244
226
245
227
In frontend programming promises are often used for network requests. So let's see an extended example of that.
246
228
247
-
We'll use the [fetch](mdn:api/WindowOrWorkerGlobalScope/fetch) method to load the information about the user from the remote server. The method is quite complex, it has many optional parameters, but the basic usage is quite simple:
229
+
We'll use the [fetch](info:fetch) method to load the information about the user from the remote server. It has a lot of optional parameters covered in [separate chapters](info:fetch), but the basic syntax is quite simple:
248
230
249
231
```js
250
232
let promise =fetch(url);
251
233
```
252
234
253
235
This makes a network request to the `url` and returns a promise. The promise resolves with a `response` object when the remote server responds with headers, but *before the full response is downloaded*.
254
236
255
-
To read the full response, we should call a method `response.text()`: it returns a promise that resolves when the full text downloaded from the remote server, with that text as a result.
237
+
To read the full response, we should call the method `response.text()`: it returns a promise that resolves when the full text is downloaded from the remote server, with that text as a result.
256
238
257
239
The code below makes a request to `user.json` and loads its text from the server:
There is also a method `response.json()` that reads the remote data and parses it as JSON. In our case that's even more convenient, so let's switch to it.
255
+
The `response` object returned from `fetch`also includes the method `response.json()` that reads the remote data and parses it as JSON. In our case that's even more convenient, so let's switch to it.
274
256
275
257
We'll also use arrow functions for brevity:
276
258
277
259
```js run
278
260
// same as above, but response.json() parses the remote content as JSON
279
261
fetch('/article/promise-chaining/user.json')
280
262
.then(response=>response.json())
281
-
.then(user=>alert(user.name)); // iliakan
263
+
.then(user=>alert(user.name)); // iliakan, got user name
282
264
```
283
265
284
266
Now let's do something with the loaded user.
285
267
286
-
For instance, we can make one more request to github, load the user profile and show the avatar:
268
+
For instance, we can make one more requests to GitHub, load the user profile and show the avatar:
The code works, see comments about the details, but it should be quite self-descriptive. Although, there's a potential problem in it, a typical error of those who begin to use promises.
290
+
The code works; see comments about the details. However, there's a potential problem in it, a typical error for those who begin to use promises.
309
291
310
292
Look at the line `(*)`: how can we do something *after* the avatar has finished showing and gets removed? For instance, we'd like to show a form for editing that user or something else. As of now, there's no way.
Now right after `setTimeout` runs `img.remove()`, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data.
341
-
342
-
As a rule, an asynchronous action should always return a promise.
322
+
That is, the `.then` handler in line `(*)` now returns `new Promise`, that becomes settled only after the call of `resolve(githubUser)` in `setTimeout``(**)`. The next `.then` in the chain will wait for that.
343
323
344
-
That makes it possible to plan actions after it. Even if we don't plan to extend the chain now, we may need it later.
324
+
As a good practice, an asynchronous action should always return a promise. That makes it possible to plan actions after it; even if we don't plan to extend the chain now, we may need it later.
345
325
346
326
Finally, we can split the code into reusable functions:
0 commit comments