Promise链式调用正确实现:车牌查询后表单提交流程控制问题
问题解决:仅在车牌查询成功时提交表单
你的问题核心是retrieveCarbonEmissions方法里的catch块捕获错误后,没有重新抛出异常,导致这个Promise最终会变成**已解决(resolved)**状态——哪怕请求失败了,外层的then还是会触发,所以saveExpense一定会执行。
要实现「成功则提交,失败则终止流程」的逻辑,需要让retrieveCarbonEmissions在请求失败时保持**拒绝(rejected)**状态,这样外层的catch才能捕获到错误,跳过saveExpense的执行。具体修改如下:
第一步:修改retrieveCarbonEmissions方法
在弹出错误提示后重新抛出错误,让Promise保持拒绝状态:
/** * Retrieves the carbon emissions for a given journey based on the distance * as well as the given license plate (if any) */ retrieveCarbonEmissions: function() { return axios.get(`/api/expenses/dvla/${this.vehicle_registration}`) .then(response => { this.carbon_emissions = (response.data.co2emission * this.miles).toFixed(2); }) .catch((error) => { this.$swal({ type: 'error', title: 'Oops...', text: 'Please enter a valid registration number in the "Car Registration" field.', }); // 重新抛出错误,让Promise保持rejected状态 throw error; }) }
第二步:完善submitExpense方法
统一处理加载器关闭逻辑,避免页面一直处于加载状态:
/** * Submit the given expense, if there is a number plate we'll try to get the CO2 emissions. */ submitExpense: function(){ this.loader = this.$loading.show({ container: this.fullPage ? null : this.$refs.editPersonalExpenseFormContainer }); // 统一关闭加载器的函数 const finishLoading = () => { this.loader?.hide(); }; if(this.vehicle_registration){ this.retrieveCarbonEmissions() .then(() => { this.saveExpense(); finishLoading(); }) .catch((error) => { console.log(error); finishLoading(); }); } else{ this.saveExpense(); finishLoading(); } },
修改说明
- 重新抛出错误后,
retrieveCarbonEmissions在请求失败时会返回rejected的Promise,外层的catch会触发,不会执行then里的saveExpense。 - 新增
finishLoading函数统一处理加载器关闭,不管成功失败都能结束加载状态,避免页面卡死。
内容的提问来源于stack exchange,提问作者Jesse Luke Orange
相关产品推荐
相关产品推荐

