Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

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.

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:

/**
 * 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.

How do I say do this and then do that, but if it fails just stop doing things?

Upvotes: 0

Views: 39

Answers (1)

trincot
trincot

Reputation: 350117

This happens because of the .catch() in retrieveCarbonEmissions. 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. In your case, it returns undefined and that means that returned promise is fulfulled, not rejected.

To make it reject, rethrow the error by adding a throw error; in that catch callback.

Upvotes: 1

Related Questions