Promise asynchronous exception handling-async and await

For fnthe asynchronous exceptions in the method , we can't catch the exception with the ordinary try...catch...method, we need to do this:

  1. promiseWrap methods that throw asynchronous exceptions
  2. With the awaitacquired fnreturn value: await fn(), awaitrole is to calculate the expression
  3. try...catchCatch exception

If you call several functions in a row, you must add the awaitsum 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

Insert picture description here
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:
Insert picture description here
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:
Insert picture description here

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
Insert picture description here

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:
Insert picture description here

Insert picture description here
Report UnhandledPromiseRejectionWarningan 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

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/114108150