Skip to content

Commit e456067

Browse files
committed
up
1 parent f2599e6 commit e456067

File tree

8 files changed

+239
-293
lines changed

8 files changed

+239
-293
lines changed

8-async/03-promise-chaining/article.md

Lines changed: 239 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ fetch('/article/promise-chaining/user.json')
228228
.then(user => alert(user.name)); // iliakan
229229
```
230230

231-
Now let's do something with it. For instance, we can make one more request to github, load the user profile and show its avatar:
231+
Now let's do something with it. For instance, we can make one more request to github, load the user profile and show the avatar:
232232

233233
```js run
234234
// 1. Make a request for user.json
@@ -250,7 +250,7 @@ fetch('/article/promise-chaining/user.json')
250250
});
251251
```
252252

253-
Now it works. But there's a potential problem in the code.
253+
The code works. But there's a potential problem in it.
254254

255255
Look at the line `(*)`: how can we do something *after* the avatar is removed? For instance, we'd like to show a form for editing that user or something else.
256256

@@ -280,9 +280,11 @@ fetch('/article/promise-chaining/user.json')
280280
.then(githubUser => alert(`Finished showing ${githubUser.name}`));
281281
```
282282

283-
An async action should always return a promise. That makes possible to plan actions after it.
283+
Now when `setTimeout` runs the function, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data.
284+
285+
As a rule, an asynchronous action should always return a promise. That makes possible to plan actions after it. Even if we don't plan to extend the chain now, we may need it later.
284286

285-
Finally, we can split it into reusable functions:
287+
Finally, we can split the code into reusable functions:
286288

287289
```js run
288290
function loadJson(url) {
@@ -316,6 +318,237 @@ loadJson('/article/promise-chaining/user.json')
316318
// ...
317319
```
318320

319-
Now when `setTimeout` runs the function, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data.
321+
## Error handling
322+
323+
Asynchronous actions may sometimes fail: in case of an error the corresponding promises becomes rejected. For instance, `fetch` fails if the remote server is not available. We can use `.catch` to handle errors (rejections).
324+
325+
Promise chaining is great at that aspect. When a promise rejects, the control jumps to the closest rejection handler down the chain. That's very convenient in practice.
326+
327+
For instance, in the code below the URL is wrong (no such server) and `.catch` handles the error:
328+
329+
```js run
330+
*!*
331+
fetch('https://no-such-server.blabla') // rejects
332+
*/!*
333+
.then(response => response.json())
334+
.catch(err => alert(err)) // TypeError: failed to fetch (the text may vary)
335+
```
336+
337+
Or, maybe, everything is all right with the server, but the response is not a valid JSON:
338+
339+
```js run
340+
fetch('/') // fetch works fine now, the server responds successfully
341+
*!*
342+
.then(response => response.json()) // rejects: the page is HTML, not a valid json
343+
*/!*
344+
.catch(err => alert(err)) // SyntaxError: Unexpected token < in JSON at position 0
345+
```
346+
347+
348+
In the example below we append `.catch` to handle all errors in the avatar-loading-and-showing chain:
349+
350+
```js run
351+
fetch('/article/promise-chaining/user.json')
352+
.then(response => response.json())
353+
.then(user => fetch(`https://api.github.com/users/${user.name}`))
354+
.then(response => response.json())
355+
.then(githubUser => new Promise(function(resolve, reject) {
356+
let img = document.createElement('img');
357+
img.src = githubUser.avatar_url;
358+
img.className = "promise-avatar-example";
359+
document.body.append(img);
360+
361+
setTimeout(() => {
362+
img.remove();
363+
resolve(githubUser);
364+
}, 3000);
365+
}))
366+
.catch(error => alert(error.message));
367+
```
368+
369+
Here `.catch` doesn't trigger at all, because there are no errors. But if any of the promises above rejects, then it would execute.
370+
371+
## Implicit try..catch
372+
373+
The code of the executor and promise handlers has an "invisible `try..catch`" around it. If an error happens, it gets caught and treated as a rejection.
374+
375+
For instance, this code:
376+
377+
```js run
378+
new Promise(function(resolve, reject) {
379+
*!*
380+
throw new Error("Whoops!");
381+
*/!*
382+
}).catch(alert); // Error: Whoops!
383+
```
384+
385+
...Works the same way as this:
386+
387+
```js run
388+
new Promise(function(resolve, reject) {
389+
*!*
390+
reject(new Error("Whoops!"));
391+
*/!*
392+
}).catch(alert); // Error: Whoops!
393+
```
394+
395+
The "invisible `try..catch`" around the executor automatically catches the error and treats it as a rejection.
396+
397+
That's so not only in the executor, but in handlers as well. If we `throw` inside `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler.
398+
399+
Here's an example:
400+
401+
```js run
402+
new Promise(function(resolve, reject) {
403+
resolve("ok");
404+
}).then(function(result) {
405+
*!*
406+
throw new Error("Whoops!"); // rejects the promise
407+
*/!*
408+
}).catch(alert); // Error: Whoops!
409+
```
410+
411+
That's so not only for `throw`, but for any errors, including programming errors as well:
412+
413+
```js run
414+
new Promise(function(resolve, reject) {
415+
resolve("ok");
416+
}).then(function(result) {
417+
*!*
418+
blabla(); // no such function
419+
*/!*
420+
}).catch(alert); // ReferenceError: blabla is not defined
421+
```
422+
423+
As a side effect, the final `.catch` not only catches explicit rejections, but also occasional errors in the handlers above.
424+
425+
## Rethrowing
426+
427+
As we already noticed, `.catch` behaves like `try..catch`. We may have as many `.then` as we want, and then use a single `.catch` at the end to handle errors in all of them.
428+
429+
In a regular `try..catch` we can analyze the error and maybe rethrow it if can't handle. The same thing is possible for promises. If we `throw` inside `.catch`, then the control goes to the next closest error handler. And if we handle the error and finish normally, then it continues to the closest successful `.then` handler.
430+
431+
In the example below the `.catch` successfully handles the error:
432+
```js run
433+
// the execution: catch -> then
434+
new Promise(function(resolve, reject) {
435+
436+
throw new Error("Whoops!");
437+
438+
}).catch(function(error) {
439+
440+
alert("The error is handled, continue normally");
441+
442+
}).then(() => alert("Next successful handler runs"));
443+
```
444+
445+
Here the `.catch` block finishes normally. So the next successful handler is called. Or it could return something, that would be the same.
446+
447+
...And here the `.catch` block analyzes the error and throws it again:
448+
449+
```js run
450+
// the execution: catch -> catch -> then
451+
new Promise(function(resolve, reject) {
452+
453+
throw new Error("Whoops!");
454+
455+
}).catch(function(error) { // (*)
456+
457+
if (error instanceof URIError) {
458+
// handle it
459+
} else {
460+
alert("Can't handle such error");
461+
462+
*!*
463+
throw error; // throwing this or another error jumps to the next catch
464+
*/!*
465+
}
466+
467+
}).then(function() {
468+
/* never runs here */
469+
}).catch(error => { // (**)
470+
471+
alert(`The unknown error has occured: ${error}`);
472+
// don't return anything => execution goes the normal way
473+
474+
});
475+
```
476+
477+
The handler `(*)` catches the error and just can't handle it, because it's not `URIError`, so it throws it again. Then the execution jumps to the next `.catch` down the chain `(**)`.
478+
479+
## Unhandled rejections
480+
481+
...But what if we forget to append an error handler to the end of the chain?
482+
483+
Like here:
484+
485+
```js untrusted run refresh
486+
new Promise(function() {
487+
errorHappened(); // Error here (no such function)
488+
});
489+
```
490+
491+
Or here:
492+
493+
```js untrusted run refresh
494+
new Promise(function() {
495+
throw new Error("Whoops!");
496+
}).then(function() {
497+
// ...something...
498+
}).then(function() {
499+
// ...something else...
500+
}).then(function() {
501+
// ...but no catch after it!
502+
});
503+
```
504+
505+
Technically, when an error happens, the promise state becomes "rejected", and the execution should jump to the closest rejection handler. But there is no such handler in the examples above.
506+
507+
Usually that means that the code is bad. Indeed, how come that there's no error handling?
508+
509+
Most JavaScript engines track such situations and generate a global error in that case. In the browser we can catch it using `window.addEventListener('unhandledrejection')` as specified in the [HTML standard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections):
510+
511+
512+
```js run
513+
window.addEventListener('unhandledrejection', function(event) {
514+
// the event object has two special properties:
515+
alert(event.promise); // [object Promise] - the promise that generated the error
516+
alert(event.reason); // Error: Whoops! - the unhandled error object
517+
});
518+
519+
new Promise(function() {
520+
throw new Error("Whoops!");
521+
}).then(function() {
522+
// ...something...
523+
}).then(function() {
524+
// ...something else...
525+
}).then(function() {
526+
// ...but no catch after it!
527+
});
528+
```
529+
530+
Now if an error has occured, and there's no `.catch`, the event `unhandledrejection` triggers, and our handler can do something with the exception. Once again, such situation is usually a programming error.
531+
532+
In non-browser environments like Node.JS there are other similar ways to track unhandled errors.
533+
534+
## Summary
535+
536+
To summarize, `.then/catch(handler)` returns a new promise that changes depending on what handler does:
537+
538+
1. If it returns a value or finishes without a `return` (same as `return undefined`), then the new promise becomes resolved, and the closest resolve handler (the first argument of `.then`) is called with that value.
539+
2. If it throws an error, then the new promise becomes rejected, and the closest rejection handler (second argument of `.then` or `.catch`) is called with it.
540+
3. If it returns a promise, then JavaScript waits until it settles and then acts on its outcome the same way.
541+
542+
The picture of how the promise returned by `.then/catch` changes:
543+
544+
![](promise-handler-variants.png)
545+
546+
The smaller picture of how handlers are called:
547+
548+
![](promise-handler-variants-2.png)
549+
550+
In the examples of error handling above the `.catch` was always the last in the chain. In practice though, not every promise chain has a `.catch`. Just like regular code is not always wrapped in `try..catch`.
551+
552+
We should place `.catch` exactly in the places where we want to handle errors and know how to handle them.
320553

321-
Here we assumed that everything works as intended. But that's not always the case. In the next chapter we'll talk about error handling.
554+
For errors that are outside of that scope we should have the `unhandledrejection` event handler. Such unknown errors are usually unrecoverable, so all we should do is to inform the user and probably report to our server about the incident.
File renamed without changes.

0 commit comments

Comments
 (0)