I'm just getting started with async/await
and running into a problem.
I can do as expected:
async function x() {
let y = await Promise.resolve(42);
return y;
}
But when I reject a Promise
:
async function bad() {
try {
await Promise.reject('bad');
} catch(err) {
err; //AssertionError: TypeError: (0 , _errorHandler2.default) is not a function
}
}
How do I catch rejected Promises
with async/await
?
You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.
Find out how to reject a Promise in async/await syntax Therefore, you simply need to throw an error inside the async function to make it reject. For example: function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function foo() { await wait(1000); throw new Error('Woops! '); } console.
Normally, such . catch doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it.
The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.
What bad;
alone is supposed to do? The error is caught as expected, you just don't do anything with it:
async function bad() {
try {
await Promise.reject('bad');
} catch(err) {
console.log(err);
}
}
bad();
This outputs bad
as expected. Code here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With