1.async使得函数变成异步,添加后依然同普通函数使用;
2.await操作符必须在async函数内使用;
3.await操作符等待的函数必须要返回的一个promise对象;
4.promise返回的是reject, await拿不到, 需要配合try catch来捕捉reject;
async function test(){
try{
var status = await Promise.resolve(200);
console.log(status); // 200
var notFound = await Promise.reject(404);
console.log(notFound); // 没有打印; ↓catch会捕捉到reject;
console.log(55) // 没有打印; 当前面返回reject,后续不再执行;
}catch(err){
console.log(err); // 404
}
}
test();
console.log(1) // 比test函数先执行,也就证明test是异步函数;
当调用test() 方法时,进入try进行判断,等待Promise.resolve(200), 因为resolve是Promise成功后的值
,所以会打印 status 但是Promise.reject() 是Promise失败后的值,try只能进行成功的操作,reject后面的值会进入到catch中,在catch中打印notFound的值。
打印的值
vue 中的案例:
情景:先渲染列表数据,等数据渲染完成 然后再执行下面的操作。再调用列表数据渲染后面,通过.then()执行下面的操作。
loadPage:async function () { // 声明函数为异步
let that = this
const pageResult = await $httpRequest({ // 等待数据请求完成
url: that.url,
param: that.query
}).then(function (res) {
if(res.resultCode) {
that.list = [...res.result.rows]
that.total = res.result.total
} else {
that.list = [...res.rows]
that.total = res.total
}
$('.fixed-table').css('overflow-x', that.list.length == 0 ? 'hidden' : 'auto')
if(!that.layPageFlag) {
that.$nextTick(function() {
that.loadLayui()
})
} else if(that.isLoadLaypage) {
that.loadLayPage()
}
that.$nextTick(function() {
that.checkBefore()
that.tableFormMethods()
that.$emit('total', that.total)
})
console.log('%c 8888888888','color:red')
return res
})
return pageResult
}
调用:
that.$refs.table.loadPage().then(resule=>{
console.log(resule,'执行下面的操作') // 此处打印的结果就是 await 返回的数据,可以根据返回的数据执行 后面的操作
})