一、用法:和java不同的是,nodejs是一个单线程函数,主线程在执行的时候,一旦发生了异步处理(文件读写、网络请求、定时任务、读取数据库等),一方面,js会让操作系统相关部件去处理这些请求,另一方面,它会继续执行后面的代码,这就是异步。如果某些场景对顺序有要求,需要同步(按顺序)执行,可以使用async搭配await实现,await函数不能单独使用。
语法如下:
async methodName(params){
let isSuccess = false;
await this.$http({
url: URL,
method: "get",
params: this.$http.adornParams({
params:params
})
}).then(({ data }) => {
if (data && data.code === 0) {
if(data.exist == 0){
isSuccess = true
}
}
}).catch(err => {
console.log(err);
this.$message({
type: "error",
message: "系统异常"
});
});
return isSuccess
}
async函数返回的是一个Promise对象,可以使用then函数添加回调函数
methodaa() {
this.methodName(this.params).then(function (result) {
if (result) {
// do sth.这里写用到result的语句
}else {
// do other sth.
}
})
}
【补充】在JS里,当然也并非所有操作都是异步的,比如for循环,无论这个for循环需要耗时多长,系统也一定会等它转完之后才会执行下面的语句
二、实例:
1、异步:如我希望以下代码按照第一、二、三、四步的顺序执行:
export default {
name: 'Default',
data() {
return {
id: ''
};
},
created() {
this.init();
},
methods: {
init() {
//第一步
let res = this.getReportId();
//第四步
this.id = res;
alert('4:' + this.id);
},
getReportId(scene) {
let id = '';
this.$api['report/getMyReports']({
roleId:'gly'
}).then(data => {
if (data && data.length > 0) {
//第二步
id = data[0].reportId;
alert('2:' + id);
}
});
//第三步
alert('3:' + id);
return id;
}
}
};
</script>
执行的结果却是:
可以看到,ajax请求最后执行,其他部分按顺序先执行了。可以修改下ajax的return顺序再验证下这个结论:
<script>
export default {
name: 'Default',
data() {
return {
id: ''
};
},
created() {
this.init();
},
methods: {
init() {
//第一步
let res = this.getReportId();
//第四步
this.id = res;
alert('4:' + this.id);
},
getReportId(scene) {
this.$api['report/getMyReports']({
scene: 7,
roleId: -1
}).then(data => {
if (data && data.length > 0) {
//第二步
alert('2:' + data[0].reportId);
return data[0].reportId;
}
});
}
}
};
</script>
执行顺序:
这会导致我在最后一步(第四步)获取的结果不准确。常用的解决方法是把第四步的赋值操作放到第二步中,即接口响应数据了再赋值。下面用另一种方法,代码同步方法来实现:
2、ajax请求同步方法:
<script>
export default {
name: 'Default',
data() {
return {
id: ''
};
},
created() {
this.getReportIds();
},
methods: {
getReportIds() {
let _this = this;
//第一步
this.getReportId().then(function(result) {
//第四步
_this.id = result;
alert('4:' + _this.id);
});
},
async getReportId(scene) {
let id = '';
await this.$api['report/getMyReports']({
roleId: 'gly'
}).then(data => {
if (data && data.length > 0) {
//第二步
id = data[0].reportId;
alert('2:' + id);
}
});
//第三步
alert('3:' + id);
return id;
}
}
};
</script>
执行结果:
更多推荐
vue 函数(一):async/await方法同步
发布评论