https://javascript.info/async-await
The async keyword before a function has two effects:
- Makes it always return a promise.
- Allows await to be used in it.
The await keyword before a promise makes JavaScript wait until that promise settles, and then:
- If it’s an error, the exception is generated — same as if throw error were called at that very place.
- Otherwise, it returns the result.
The following are same
async function f() {
await Promise.reject(new Error("Whoops!"));
}
async function f() {
throw new Error("Whoops!");
}
We can catch that error using try..catch, the same way as a regular throw:
async function f() {
try {
let response = await fetch('http://no-such-url');
} catch(err) {
alert(err); // TypeError: failed to fetch
}
}
f();
If we don’t have try..catch, then the promise generated by the call of the async function f() becomes rejected. We can append .catch to handle it:
async function f() {
let response = await fetch('http://no-such-url');
}
// f() becomes a rejected promise
f().catch(alert); // TypeError: failed to fetch // (*)
If we forget to add .catch there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global unhandledrejection event handler as described in the chapter Error handling with promises.
An example for error handling in mongoose
mongoose.connect('mongodb://127.0.0.1:27017/test').
catch(error => handleError(error));
// Or:
try {
await mongoose.connect('mongodb://127.0.0.1:27017/test');
} catch (error) {
handleError(error);
}