[英]Promise chaining the correct way
I have a form where if users enter a number plate I want to look up the data and set a Vue data property before submitting the data.我有一个表单,如果用户输入车牌,我想在提交数据之前查找数据并设置 Vue 数据属性。
I have a method to achieve this:我有一个方法来实现这一点:
/**
* 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.',
});
})
}
I am using return
so that the Promise is returned so that I can use it in method chaining like so:我正在使用return
以便返回 Promise 以便我可以在方法链接中使用它,如下所示:
/**
* 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();
}
},
However, the inner method will run after the promise is resolved, irrespective of whether it fails.但是,无论是否失败,内部方法都会在 promise 解决后运行。
How do I say do this and then do that, but if it fails just stop doing things?我怎么说做这个然后做那个,但如果它失败了就停止做事?
This happens because of the .catch()
in retrieveCarbonEmissions
.发生这种情况是因为retrieveCarbonEmissions
中的.catch()
。 When the promise -- on which this .catch()
is chained -- rejects, then its callback determines the resolution of the promise that .catch()
(and thus retrieveCarbonEmissions
) returns.当 promise —— .catch()
被链接——拒绝时,它的回调确定.catch()
(以及因此retrieveCarbonEmissions
)返回的 promise 的分辨率。 In your case, it returns undefined
and that means that returned promise is fulfulled , not rejected .在您的情况下,它返回undefined
,这意味着返回的promise is fulfulled , not denied 。
To make it reject, rethrow the error by adding a throw error;
要使其拒绝,请通过添加throw error;
in that catch
callback.在那个catch
回调中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.