hantoren
hantoren

Reputation: 1265

Structure promise chain

Is there any way to better structure the code? In particular how exceptions are handled within a "promise chain"?

$("#save").click(function(e) {
    e.preventDefault();

    let $self = $(this);
    let profile = {}

    $self.prop("disabled", true)

    profile['oldPassword'] = $('#oldPassword').val();
    profile['newPassword'] = $('#newPassword').val();

    Profile.validateForm(profile).then(() => {
        Profile.sendAjax(profile).then(() => {
            $('#oldPassword').val('');
            $('#newPassword').val('');
            $("#profileAlert").text('Password changed successully').removeClass('alert-danger').addClass('alert-success').show().delay(5000).fadeOut()
        }).catch(e => {
            $("#profileAlert").text(e).removeClass('alert-success').addClass('alert-danger').show()
        }).finally(() => {
            $self.prop("disabled", false)
        })
    }).catch(e => {
        $("#profileAlert").text(e).removeClass('alert-success').addClass('alert-danger').show()
    }).finally(() => {
        $self.prop("disabled", false)
    })
});

Upvotes: 0

Views: 38

Answers (1)

sp00m
sp00m

Reputation: 48837

Given your catch and finally callbacks behave the same, you can safely chain the promises:

Profile.validateForm(profile).then(() => {
  return Profile.sendAjax(profile);
}).then(() => {
  $('#oldPassword').val('');
  $('#newPassword').val('');
  $("#profileAlert").text('Password changed successully').removeClass('alert-danger').addClass('alert-success').show().delay(5000).fadeOut()
}).catch(e => {
  $("#profileAlert").text(e).removeClass('alert-success').addClass('alert-danger').show()
}).finally(() => {
  $self.prop("disabled", false)
})

Upvotes: 3

Related Questions