当前位置:网站首页>Async/await you can use it, but do you know how to deal with errors?

Async/await you can use it, but do you know how to deal with errors?

2022-07-05 01:03:00 Sunshine_ Lin

Preface

Hello everyone , I'm Lin Sanxin , Speak the most difficult knowledge points in the most easy to understand words It's my motto , Foundation is the premise of advanced It's my first heart

Promise Encapsulation request

If you usually use Promise Encapsulation request , So when you use this request function, it's like this :

//  Encapsulation request function 
const request = (url, params) => {
  return new Promise((resolve, reject) => {
    // ...do something
  })
}

//  When using 
const handleLogin = () => {
  request(
    '/basic/login',
    {
      usename: 'sunshine',
      password: '123456'
    }
  ).then(res => {
    // success do something
  }).catch(err => {
    // fail do something
  })
}

You can see , When your request is successful , Would call then Method , When your request fails catch Method .

async/await

Promise It solves a lot of problems , But if there are too many requests and there are order requirements , It's hard to avoid it nesting The problem of , Poor readability , such as :

const handleLogin = () => {
  request(
    '/basic/login',
    {
      usename: 'sunshine',
      password: '123456'
    }
  ).then(res => {
    //  Obtain user information after successful login 
    request(
      '/basic/getuserinfo',
      res.id
    ).then(info => {
      this.userInfo = info
    }).catch()
  }).catch(err => {
    // fail do something
  })

So at this point async/await There is , His function is : Perform asynchronous operations in a synchronous manner , The above code is used async/await It can be rewritten as :

const handleLogin = async () => {
  const res = await request('/basic/login', {
    usename: 'sunshine',
    password: '123456'
  })
  const info = await request('/basic/getuserinfo', {
    id: res.id
  })
  this.userInfo = info
}

In this case, the readability of the code is relatively high , Without the nesting problem just now , But now there's another problem ,Promise Yes catch This error callback ensures what to do after a request error , however async/await How to catch errors ?

async-to-js

In fact, there is already a library async-to-js Has done this for us , We can see how it's done , Its source code is only Just a dozen lines , We should read its source code , Learn its thoughts

The source code is very simple

/**
 * @param { Promise }  The request function passed in 
 * @param { Object= } errorExt -  Expand the wrong object 
 * @return { Promise }  Return to one Promise
 */
export function to(
  promise,
  errorExt
) {
  return promise
    .then(data => [null, data])
    .catch(err => {
      if (errorExt) {
        const parsedError = Object.assign({}, err, errorExt)
        return [parsedError, undefined]
      }

      return [err, undefined]
    })
}

export default to
Source code summary : to The function returns a Promise And the value is an array , There are two elements in the array , If the index is 0 The element of is not null , It indicates that the request reports an error , If the index 0 The element of is null, indicating that the request does not report an error , That's success .

It's easy to use

How do we use this to Function? ? It's very simple , It's just an example

const handleLogin = async () => {
  const [resErr, res] = await to(request('/basic/login', {
    usename: 'sunshine',
    password: '123456'
  }))
  if (resErr) {
    // fail do somthing
    return
  }
  const [userErr, info] = await to(request('/basic/getuserinfo', {
    id: res.id
  }))
  if (userErr) {
    // fail do somthing
    return
  }
  this.userInfo = info
}

So , Occasionally look at the source code of some libraries , You can still learn something !!!

Conclusion

I'm Lin Sanxin , An enthusiastic front-end rookie programmer . If you make progress , Like the front , Want to learn the front end , Then we can make friends , Fish together, ha ha , Fish schools , Add me, please note 【 Think no 】

image.png

原网站

版权声明
本文为[Sunshine_ Lin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141058433802.html

随机推荐