0
\$\begingroup\$

I have this function and looks ugly because there are a lot of "catch" doing the same. Any idea how to make it better?

saveUser: function(){
    let user_id = this.$route.params.user_id;
    let payload = this.user;

    updateUser(user_id, payload).then(response => {
        updateOrCreateAddresses(payload).then(response => {
            updateOrCreateBalances(payload).then(response => {
                this.success();
            }).catch(error => {
                this.showError(error)
            })
        }).catch(error => {
            this.showError(error)
        })
    }).catch(error => {
        this.showError(error)
    })
},
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review! Your question has to describe what you are actually trying to accomplish in as much detail as possible. With not much code and basically no context, it is unlikely to get meaningful reviews. \$\endgroup\$ – AlexV Jun 21 at 10:13
  • \$\begingroup\$ Hello @AlexV, I want to improve or make the code looks a bit better. Having the catches repeated may not be the best practice \$\endgroup\$ – dkn15 Jun 21 at 10:18
  • 2
    \$\begingroup\$ My question was not what you expect from the review, but the type of application this code is used for (your use-case). \$\endgroup\$ – AlexV Jun 21 at 11:12
1
\$\begingroup\$

As I am not sure on how your Promises work, this is what I can come up with.

To reduce your catch nesting you could make each promise return another promise. This would force you to have a general .then and a general .catch after your updateUser method.

I stubbed a bit of code here:

var updateUser = new Promise(function(resolve, reject) {
  resolve("Promise one");
});

var updateOrCreateAddresses = new Promise(function(resolve, reject) {
  reject("Promise two"); // e.g. replace reject with resolve to see it "pass"
});

var updateOrCreateBalances = new Promise(function(resolve, reject) {
  resolve("Promise three");
});

var success = () => {
    alert("Success");
}

updateUser.then( x => {
    return updateOrCreateAddresses.then(y => {
        return updateOrCreateBalances.then(z => {
            return success;
        })
    })
})
.then(a => a())
.catch(err => alert(err));

What happens there? Each promise is returning another promise. If one promise fails, the promise will return the "error" to it's parent, where on updateUser the promise get's finally caught.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.