JavaScript, async and await keywords

Magus
464 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

As you should already know, a promise can be rejected. So you should ask yourself: How do we deal with a rejected promise when using async and await ? If you remember the playground on promises, you learned this:

You can use the promise's catch like a normal catch. And everything is simple to understand. Keep in mind that a then callback can crash. It can throw an error (with an explicit throw or by trying to access a property of a null variable). The catch method will also catch these crashes. Repeat to yourself: the promise's catch method is like a normal catch.

So, what is the most natural way to handle an error when using async and await ? Yes, you have it. Use a simple try { ... } catch (error) { ... }. Look at the following example:

Error handling example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function job() {
return new Promise(function(resolve, reject) {
setTimeout(reject, 500, 'Error happened');
});
}
async function test() {
try {
let message = await job();
console.log(message);
return 'Hello world';
} catch (error) {
console.error(error);
return 'Error happened during test';
}
}
test().then(function(message) {
console.log(message);
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

If you want to return a rejected promise in an async function, you just have to throw an error. Look at this example:

Return a rejected promise
1
2
3
4
5
6
7
8
9
10
11
12
13
async function job() {
throw new Error("Access denied");
}
job()
.then(function(message) {
console.log(message);
})
.catch(function(error) {
console.log(error);
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content