Reputation: 1265
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
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