In Vue, the async and await keywords are used to optimize the axios request/promise object to make the asynchronous programming of the project more concise

  • Traditional asynchronous programming: (xhr request, ajax request)

  • $ajax.get() in jquery through the callback function is easy to form callback hell

  • Send requests through the promise.then.catch method. For example, axios is based on promise encapsulation

created(){
    
    
    this.$http
    .get('url地址''传入的参数')
    .then(resp=>{
    
    
        //返回的数据
        console.log(resp)
    }).catch(err=>{
    
    
        //捕获到的错误信息
        console.log(err)
    })
}

Through async and await

async created(){
    
    
    //此时 resp的返回值就是一个promise对象
    const resp = this.$http('url地址')
    
    //通过await 来修饰请求
    const resp = await this.$http('url地址')
    //此时 resp就是 promise.then方法的返回值
    //注意:await不能直接使用,需要在方法前加上async关键字,否则会报错
}

important point

  • await can only modify promise objects
  • The await keyword must be written in the async function

Coupled with the await keyword will hinder the operation of the program, which belongs to synchronous programming. That is to say, the subsequent code in the function must be executed after the request ends, but it will not affect the previously requested code. Async belongs to asynchronous programming.

Guess you like

Origin blog.csdn.net/DDD4V/article/details/114980417