使用aoixs实现同步
一般使用axios进行数据请求就是要使用异步请求,但是很多时候需要同步请求,所以async
+await
了解一下:
async用于声明一个函数是异步的,await用于声明在一个异步函数中等待语句执行完毕。也就是说await只能在async函数中使用
基本用法就是这样的:
methods: { async funA(){ var res = await axios.post('') //这里的res就是axios请求回来的结果 } }
在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() ... }, }
版权声明:
作者:广州前端开发
链接:https://www.develophm.com/index.php/%e4%bd%bf%e7%94%a8aoixs%e5%ae%9e%e7%8e%b0%e5%90%8c%e6%ad%a5/888/
来源:开发之家
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
共有 0 条评论