• Es7 added async and await processing, making promise operation more concise and elegant

  • For example, when retrieving data in a common AXIos request:

    • The traditional way of writing promise

    • getxxx(){
        this.$http.post(url,param)
        .then(res= >{
          console.log(res.data);
        })
        .catch(err= >{
          console.log(err); })}Copy the code
    • This is nice and clear, of course, but when we have a project with lots of interfaces and more requests to make, it can feel a bit bloated and unelegant

    • Es7 async,await

    • async getxxx(){
        const {data} = await this.$http.post(url,param)
        console.log(data);
      }
      Copy the code
    • So it looks pretty simple and elegant

  • But some problems encountered in practical developing, when we use in learning phase axios sends the request, often will only consider success callback and ignores abnormal correction, the actual development, in order to users to better use of the experience, abnormal, we also need to be in the user interface can have a clear message, rather than the user waiting for nothing let

  • The following describes simple async exception handling

    • Using a try… Catch block to catch exceptions, the above async,await can be more complete

    • async getxxx(){
          try {
              const {data} = await this.$http.post(url,param)
              console.log(data)
          }catch(err){
              console.log(err)
          }
      }
      Copy the code
  • This looks good, but in practice, every async async requires a try, and catch is a bit bloated and unelegant. Even in Java code, I don’t use try very much… Catch, so try… Catch will appear very abrupt, I read a lot of content on the Internet, and I also see a better solution.

    • We should always know that await is a promise. We can try to print the result without await in async functions.

    • Since await itself is a promise, we provide an idea for uniform exception capture. Before await await a promise, we first encapsulate a function ourselves and uniformly handle the current promise with a correct exception acquisition

    • export default function handle(promise){
        return promise.then(data= >{
          return data
        }).catch(err= >{
          return err
        })
      }
      Copy the code
    • With such a function wrapped, we can use it to do a processing on the await promise

    • async getxxx(){
          const {err,data} = await handle(this.$http.post(url,param))
          if(err) console.log(err)
          console.log(data)
      }
      Copy the code
  • The above example is just a simple use case for this solution. You can attach interceptors to the JS file of the Handle method, which will receive the original error object, log it, or do whatever is necessary before passing it back.