async checkNum() {
let num = Math.floor(Math.random() * 10);
if (num < 5) return { result: true, num };
else throw { result: false, num };
}
this.checkNum().then((data) => {
console.log(`resolve, ${data.num}低於中間值`); // 調用Promise.resolve(),返回Promise對象
}, (data) => {
console.log(`reject, ${data.num}高於中間值`); // 調用Promise.reject(),返回Promise對象
})
帶async關鍵字的方法返回的是Promise對象
將網絡請求轉換爲async方法
getLocation(phoneNum) {
return axios.post('phoneLocation', {
phoneNum
})
}
// 點擊事件
async getFaceResult () {
try {
let location = await this.getLocation(this.phoneNum);
if (location.data.success) {
let province = location.data.obj.province;
let city = location.data.obj.city;
let result = await this.getFaceList(province, city);
if (result.data.success) {
this.faceList = result.data.obj;
}
}
} catch(err) {
console.log(err);
}
}