首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >承诺用正确的方式链接

承诺用正确的方式链接
EN

Stack Overflow用户
提问于 2022-09-06 14:57:24
回答 1查看 29关注 0票数 0

我有一个表单,如果用户输入一个号码板,我希望在提交数据之前查找数据并设置Vue data属性。

我有办法做到这一点:

代码语言:javascript
复制
/**
 * 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,以便返回承诺,以便在方法链中使用它,如下所示:

代码语言:javascript
复制
/**
 * 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();
    }
},

但是,内部方法将在承诺被解决后运行,而不管它是否失败。

我怎么说做这个然后做那个,但是如果它失败了,就停止做事情吧?

EN

回答 1

Stack Overflow用户

发布于 2022-09-06 15:03:15

发生这种情况的原因是.catch() in retrieveCarbonEmissions。当承诺--这个.catch()是链式的--拒绝时,它的回调决定了.catch() (以及因此retrieveCarbonEmissions)返回的承诺的分辨率。在您的例子中,它返回undefined,这意味着返回的承诺是满的,而不是拒绝。

若要使其拒绝,请通过在该throw error;回调中添加一个catch重新抛出错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73624094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档