For fn
the asynchronous exceptions in the method , we can't catch the exception with the ordinary try...catch...method, we need to do this:
promise
Wrap methods that throw asynchronous exceptions- With the
await
acquiredfn
return value:await fn()
,await
role is to calculate the expression try...catch
Catch exception
If you call several functions in a row, you must add the await
sum at each call that may throw an exceptionasync
Let's look at the following example:
function func1() {
func2()
}
async function func2() {
try {
console.log(await func3())
} catch (error) {
console.log('error')
}
}
async function func3(){
await setTimeout(()=>{
throw new Error('error')
},1000)
}
The above code throws an error in func3, but it will not be caught by func2 (error will not be printed), and the console.log(await func3())
printed result is undefined
If you want func2 to catch the asynchronous error in func3, you need to wrap the function that throws asynchronous error in func3, and wrap it into a promise:
so you can try...catch...in func2 to catch the asynchronous exception, in func2, await func3()
For the promise returned by func3() 求值
, the execution continues when the promise is fulfilled, and the exception is caught when the promise is rejected
Note that reject is used here, not throw:
function func1() {
func2()
}
async function func2() {
try {
await func3()
} catch (error) {
console.log('error')
}
}
function func3() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const r = Math.random()
if (r < 0.5) {
reject('error')
}
}, 1000)
})
}
func1()
In this way, you can catch the exception and print out the error
One more thing to note is that we did not use await to handle exceptions thrown by promises externally. Let's take a look at the await in the code just now:
Report UnhandledPromiseRejectionWarning
an error, because after the promise reject, the place where func3 is called in the outer layer does not use await to calculate the return result of the Promise and throw an exception