axios同步请求--
一般使用axios进行数据请求就是要使用异步请求,因为项目需求,需要同步请求,所以async+await了解一下:async用于声明一个函数是异步的,await用于声明在一个异步函数中等待语句执行完毕。也就是说await只能在async函数中使用基本用法就是这样的:methods: {async funA(){var res =await axios.post...
·
一般使用axios进行数据请求就是要使用异步请求,因为项目需求,需要同步请求,所以async
+await
了解一下:
async用于声明一个函数是异步的,await用于声明在一个异步函数中等待语句执行完毕。也就是说await只能在async函数中使用
基本用法就是这样的:
methods: {
async funA(){
var res = await axios.post('') //这里的res就是axios请求回来的结果
}
}
我这边是用在项目里的
common.js
async addImg(file, config) {
return await axios.post(path.addImage, file, config);
}
vue页面
methods:{
async upload() {
var self = this;
var formData;
for (let i = 0; i < this.imgList.length; i++) {
const img = this.imgList[i];
formData = new FormData();
formData.append("file", img);
formData.append("type", "goods_grade");
console.log(formData.getAll("file"));
await this.$api.common
.addImg(formData, {
headers: { "Content-Type": "multipart/form-data" }
})
.then(res => {
if (res.data.code == 200) {
this.$message({
type: "success",
message: "添加成功"
});
this.uploadSuccess = true;
this.childrenImgs.push(res.data.result);
this.$emit("change", this.childrenImgs);
} else {
this.$message({
type: "warning",
message: res.data.message
});
}
});
}
}
}
注意事项
如果同步请求是封装在其他函数中,那么每一个函数都需要做成异步函数。如下所示
methods: {
fun1: async function () {
await axios.get('url)
},
fun2: async function () {
...
await this.fun1()
...
},
fun3: async function () {
...
await this.fun2()
...
},
}
更多推荐
已为社区贡献2条内容
所有评论(0)