Skip to content

Commit 08e2dbd

Browse files
authored
Improved promises error handling
1 parent fc9761f commit 08e2dbd

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

readme.md

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,6 +1357,8 @@ fetchPostById('gzIrzeo64')
13571357

13581358
Unless we add *try / catch* blocks around *await* expressions, uncaught exceptions – regardless of whether they were raised in the body of your *async* function or while it’s suspended during *await* – will reject the promise returned by the *async* function. [(Ref: PonyFoo)](https://ponyfoo.com/articles/understanding-javascript-async-await#error-handling).
13591359

1360+
> **Note :** Promises behave the same!
1361+
13601362
With promises, here is how you would handle the error chain:
13611363

13621364
```js
@@ -1365,29 +1367,19 @@ function getUser() { // This promise will be rejected!
13651367
};
13661368

13671369
function getAvatarByUsername(userId) {
1368-
return new Promise((res, rej) =>
1369-
getUser(userId)
1370-
.then(user => res(user.avatar))
1371-
.catch(err => rej(err))
1372-
);
1370+
return getUser(userId).then(user => res(user.avatar))
13731371
}
13741372

13751373
function getUserAvatar(username) {
1376-
return new Promise((res, rej) =>
1377-
getAvatarByUsername(username)
1378-
.then(avatar => res({ username, avatar }))
1379-
.catch(err => rej(err))
1380-
);
1374+
return getAvatarByUsername(username).then(avatar => res({ username, avatar }))
13811375
}
13821376

13831377
getUserAvatar('mbeaudru')
13841378
.then(res => console.log(res))
13851379
.catch(err => console.log(err)); // "User not found !"
13861380
```
13871381

1388-
If you forgot a *catch*, the error will be uncaught!
1389-
1390-
But with *async* functions, if an error is thrown in it's body the promise will reject:
1382+
With *async / await*:
13911383

13921384
```js
13931385
function getUser() { // This promise will be rejected!

0 commit comments

Comments
 (0)