Overview of VUE04_Promise, commonly used APIs, static methods, axios based on different request parameters, interceptors, async/await usage

Article Directory

①. Overview and use of Promise

①. Promise is a solution for asynchronous programming. Syntactically speaking, Promise is an object from which asynchronous operation messages can be obtained

②. Benefits

  1. Can avoid multi-layer asynchronous call nesting problem (callback hell)
  2. Promise objects provide a concise API, making it easier to control asynchronous operations
  • ③. Specific steps to use:
    Instantiate the Promise object, pass the function in the constructor, the function is used to process asynchronous tasks, the
    resolve and reject parameters are used to handle both success and failure, and the processing result is obtained through p.then
var p = new Promise(function (resolve, reject) {
    setTimeout(() => {
        if (false) {
            resolve('TANGZHI');
        } else {
            reject('ERROR');
        }
    }, 2000);
});
p.then(function (ret) {
    //这是成功调用的结果
    console.log(ret);
},function(ret){
    //这是失败的结果
    console.log(ret);
});

②. Promise commonly used API (instance method)

①. .then(): get the correct result of the asynchronous task

②. .catch(): Get exception information

③. .finally(): It will be executed if it succeeds or not (not a formal standard)

 <script>
  //console.dir():可以显示一个对象所有的属性和方法,用来对一个对象进行检查(inspect),并以易于阅读和打印的格式显示。
  //console.dir(Promise);
  //第一种方法
  function po(){
      return new Promise(function(resolve,reject){
         setTimeout(function(){
             //resolve('hello xiaozhi');
             reject('Error');
         },3000);
      });
  }
  //第一种方式
  po()
  //方法成功时会调用这里
  .then(reponse=>{
     console.log(reponse);
  })
  //方法失败时会调用这里
  .catch(reponse=>{
     console.log(reponse);
  })
  //无论方法是否成功,这里都会被调用
  .finally(()=>
     console.log('finished')
   );
  //第二种方式 
  //[第一种方式和第二种方式是等价的]
  po()
  .then(function(ret){
     //这里是成功后的回调
     console.log(ret)
  },function(ret){
     //这里是失败后的回调
     console.log(ret);
  })
  .finally(()=>{
     alert("第二种方式finally...") 
  });
 </script>

③. Static method in Promise

①. Promise.all() accepts an array of Promise objects as a parameter, and its return parameter is also an array. When all the promises are resolved, it will enter the .then() method. As long as one promise is reject, it will enter .catch() to
process multiple asynchronous tasks concurrently, and all tasks will be executed to get the result.

②. Promise.race() accepts the same parameters as Promise.all(). The difference is that it will identify the promise object that reaches the resolve or reject the fastest. If this is the fastest resolve, enter the .then() method, If it is reject, enter the .catch() method.
Concurrently process multiple asynchronous tasks, as long as one task is completed, you can get the result

Insert picture description here

④. Introduction of axios

①. Support browser, node.js, Promise

②. Automatically convert JSON data, can convert request and response data

③. Ability to intercept requests and responses (powerful)

⑤. Basic usage of axios (get and delete)

①. Pass parameters in the form of? Through traditional url

②. Pass parameters in restful form

③. Pass parameters in the form of params (convenient)

 <script src="../js/axios.js"></script>
 <script src="../js/vue.js"></script>
 <script>
  //1. 发送get 请求
  //通过传统的url 以 ? 的形式传递参数
  axios.get('http://127.0.0.1:30021/staffSelect/list?page=1&&limit=10').then(response=>{
       //注意data属性是固定的用法,用于获取后台的实际数据
       console.log(response.data);//Object { code: 0, msg: "", data: (10) […], count: 27476 }
       console.log(response);//Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
   });
   //2.发送get请求
   //restful 形式传递参数 http://127.0.0.1:30021//menu/get/{}
   axios.get('http://127.0.0.1:30021//menu/get/1').then(function(reponse){
       //Object { result: true, data: {…}, msg: "查询成功" }
       console.log(reponse.data);
   });
  //3. 通过params形式传递参数
   axios.get('http://127.0.0.1:30021/staffSelect/list',{
         params:{
             page:1,
             limit:10
     }
   }).then(response=>{
       //注意data属性是固定的用法,用于获取后台的实际数据
       console.log(response.data);//Object { code: 0, msg: "", data: (10) […], count: 27476 }
       console.log(response);//Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
   });
 //4. axios delete 请求传参 传参的形式和 get 请求一样
 axios.delete('http://localhost:3000/axios', {
   params: {
       id: 111
   }
 }).then(rep=>{
     console.log(rep.data);
 });
 </script>

⑥. Basic usage of axios (post and put)

①. For the traditional way we need to use new URLSearchParams()

②. Post request is a parameter transfer in json format

 <script>
    //通过选项传递参数(默认传递的是json格式的数据)
    //{uname:'lisi',pwd:123}
    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function (ret) {
      console.log(ret.data)
    });
    //对于传统的方式我们需要创建一个URLSearchParams对象(application/x-www-form-urlencoded)
    //将参数append进去
    //传递参数的格式  uname=zhangsan&pwd=111 
    var params = new URLSearchParams();
    params.append('uname', 'zhangsan');
    params.append('pwd', '111');
    axios.post('http://localhost:3000/axios', params).then(function (ret) {
      console.log(ret.data)
    })

    // axios put 请求传参
    axios.put('http://localhost:3000/axios/123', {
      uname: 'lisi',
      pwd: 123
    }).then(function (ret) {
      console.log(ret.data)
    })
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });
  </script>

⑦. The response result of axios

①. data: the actual response data

②. status: response transition code (200 means success)

③. headers: the information of the corresponding header

④. statusText: response status information

⑧. Axios global configuration

①. Configure the public request header
axios.defaults.baseURL ='https://api.example.com';

②. Configure the timeout time
axios.defaults.timeout = 2500;

③. Configure the common request header
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

④. Configure the Content-Type of the public post
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
add this parameter, then the parameter format is uname=zhangsan&pwd =111
In axios, we use JSON format to pass parameters by default

Insert picture description here

⑨. axios interceptor

  • ①. Request interceptor
  1. The role of the request interceptor is to perform some operations before the request is sent
  2. For example, adding a token to each request body, and the unified processing is very easy if you want to change it in the future
   	//请求拦截器
   axios.interceptors.request.use(config => {
       console.log(config.url);
       config.headers.myToken = 'xiaozhi';
       return config;
   }, error => {
       console.log(error);
   });
  • ②. Response interceptor
  1. The role of the response interceptor is to perform some operations after receiving the response
  2. For example, when the server returns that the login status is invalid and needs to log in again, jump to the login page
     //响应拦截器
     axios.interceptors.response.use(reponse => {
         //这里的reponse和axios.get().then(response) 是一样的
         //注意:如果这里data做了处理,那么在axios.get().then(response) 中得到的data就是这里return回去的
         var data = reponse.data;
         console.log("----" + data);
         return data;
     }, error => {
         console.log(error);
     });

     axios.get('http://127.0.0.1:30021/staffSelect/list?page=1&&limit=10').then(response => {
         //注意data属性是固定的用法,用于获取后台的实际数据
         //console.log(response.data);//Object { code: 0, msg: "", data: (10) […], count: 27476 }
         //这里的response是真实的数据,我们在响应拦截器中做了处理
         console.log(response);//Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
     });

⑩. Async/await usage

①. Put async as a keyword in front of the function.
Any async function will implicitly return a promise

②. The await keyword can only be used in a function defined by async. Await can
be directly followed by a Promise instance object. The
await function cannot be used alone.

③. async/await makes asynchronous code look and behave more like synchronous code

    // 1.  async 基础用法
    // 1.1 async作为一个关键字放到函数前面
	async function queryData() {
      // 1.2 await关键字只能在使用async定义的函数中使用      await后面可以直接跟一个 Promise实例对象
      var ret = await new Promise(function(resolve, reject){
        setTimeout(function(){
          resolve('nihao')
        },1000);
      })
      // console.log(ret.data)
      return ret;
    }
	// 1.3 任何一个async函数都会隐式返回一个promise   我们可以使用then 进行链式编程
    queryData().then(function(data){
      console.log(data)
    })

	//2.  async    函数处理多个异步函数
    axios.defaults.baseURL = 'http://localhost:3000';

    async function queryData() {
      //2.1  添加await之后 当前的await 返回结果之后才会执行后面的代码   
      
      var info = await axios.get('async1');
      //2.2  让异步代码看起来、表现起来更像同步代码
      var ret = await axios.get('async2?info=' + info.data);
      return ret.data;
    }

    queryData().then(function(data){
      console.log(data)
    })