我有一个表单,如果用户输入一个号码板,我希望在提交数据之前查找数据并设置Vue data属性。
我有办法做到这一点:
/**
* 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) => {
// console.log(error.response);
this.$swal({
type: 'error',
title: 'Oops...',
text: 'Please enter a valid registration number in the "Car Registration" field.',
});
})
}我使用return,以便返回承诺,以便在方法链中使用它,如下所示:
/**
* 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
});
if(this.vehicle_registration){
this.retrieveCarbonEmissions()
.then((response) => {
this.saveExpense();
}).catch((error) => {
console.log(error);
});
} else{
this.saveExpense();
}
},但是,内部方法将在承诺被解决后运行,而不管它是否失败。
我怎么说做这个然后做那个,但是如果它失败了,就停止做事情吧?
发布于 2022-09-06 15:03:15
发生这种情况的原因是.catch() in retrieveCarbonEmissions。当承诺--这个.catch()是链式的--拒绝时,它的回调决定了.catch() (以及因此retrieveCarbonEmissions)返回的承诺的分辨率。在您的例子中,它返回undefined,这意味着返回的承诺是满的,而不是拒绝。
若要使其拒绝,请通过在该throw error;回调中添加一个catch重新抛出错误。
https://stackoverflow.com/questions/73624094
复制相似问题