VueJS中如何等待Axios请求返回数据后再执行后续操作
解决VueJS中POST请求提前执行的问题
问题核心是getFieldPosition为异步函数,直接赋值给this.model.position会得到Promise对象,且addFieldData未等待模型填充完成就发起请求。按以下方式修改代码即可解决:
修改步骤
- 将
populateModel改为异步函数,内部通过await获取getFieldPosition的真实返回值 - 在
addFieldData中等待populateModel执行完毕后,再发送POST请求 - 调整
getFieldPosition的逻辑,直接返回接口返回的计数,后续在populateModel中计算最终position值
修改后的完整代码
async addFieldData(data, generatorData) { await this.populateModel(data); // 等待模型填充完成 console.log(this.model); try { const res = await this.$axios.post('data/webform/fields', this.model); console.log(res); this.$notify({ group: "app", title: this.$t("general.success"), text: this.$t("general.action_has_been_processed"), type: "info" }); } catch (error) { this.$notify({ group: "app", title: this.$t("general.error"), text: this.$t("general.error_occured"), type: "error" }); console.log(error); } }, async populateModel(data) { this.model.label = data.label ?? {}; this.model.hint = data.placeholder ?? {}; this.model.attributes = data.attributes ?? {}; this.model.maxlength = data.maxlength ?? 0; // 等待异步接口返回计数,再计算position const positionCount = await this.getFieldPosition(); this.model.position = positionCount + 1; this.model.required = data.required ?? true; this.model.visible = data.visible ?? true; this.model.disabled = data.disabled ?? false; this.model.style_classes = data.style_classes ?? ""; this.model.model = data.model ?? ""; this.model.default = data.default ?? ""; this.model.input_type = data.input_type ?? ""; this.model.hint = data.hint ?? ""; this.model.help = data.help ?? ""; this.model.type = data.type; }, async getFieldPosition() { const res = await this.$axios.get('/data/webform/' + this.idWebform + '/itemsCount'); return res.data.data.count; // 直接返回接口计数,后续统一计算position }
关键说明
- 异步流程控制:通过
await关键字确保异步操作完成后再执行后续代码,彻底解决请求顺序混乱的问题 - 避免Promise赋值:原代码中直接将
getFieldPosition()赋值给this.model.position,实际存入的是Promise对象而非数值,await处理后可获取真实的计数结果 - 代码可读性优化:将POST请求的
.then/.catch改为async/await风格的try/catch,逻辑更直观
内容的提问来源于stack exchange,提问作者Matyas Zednicek
相关产品推荐
相关产品推荐

