在vue项目里定义了一个全局函数,如下:
每次都返回空数组。因为接口调用后还未返回数据,该函数就将result return了。
Vue.prototype.getCity = function(){//获取城市列表
var result = [];
getCityList().then(res=>{
if(res.code==0){
//console.log(res.data);
result = res.data;
}else{
result =[];
_this.$message({
message: res.message,
type: 'error',
duration:1500
});
}
});
return result
}
改用 async await 写法,等接口返回数据了再return。
实现代码如下:
1、给函数增加 async await
// async await的写法
Vue.prototype.getCity = async function(){//获取城市列表
var result = [];
await getCityList().then(res=>{
if(res.code==0){
//console.log(res.data);
result = res.data;
}else{
result =[];
_this.$message({
message: res.message,
type: 'error',
duration:1500
});
}
});
return result
}
2、页面调用时的写法:
async getCityList(){//获取城市列表
_this.cityLoading=true;
_this.cityArr = await _this.getCity();
_this.cityLoading=false;
//console.log(_this.cityArr);
},
3、返回结果如下,现在不再返回空数组了:
: