-
传统异步编程:(xhr请求,ajax请求)
-
通过回调函数在jquery中$ajax.get()容易形成回调地狱
-
通过promise .then .catch方法发送请求 例如axios就是基于promise封装的
created(){
this.$http
.get('url地址','传入的参数')
.then(resp=>{
//返回的数据
console.log(resp)
}).catch(err=>{
//捕获到的错误信息
console.log(err)
})
}
通过async与await
async created(){
//此时 resp的返回值就是一个promise对象
const resp = this.$http('url地址')
//通过await 来修饰请求
const resp = await this.$http('url地址')
//此时 resp就是 promise.then方法的返回值
//注意:await不能直接使用,需要在方法前加上async关键字,否则会报错
}
注意点
- await只能修饰promise对象
- await关键字必须写在async函数内
再加上await关键字后会阻碍程序的运行,属于同步编程。也就是说必须在请求结束后才会执行函数内后续的代码,但是不会影响前面请求的代码,async属于异步编程。