genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Handle promises within if...else #110

Open genkio opened 7 years ago

genkio commented 7 years ago

before refactor

if (isEditMode) {
  $comment.editComment(comment.id, comment)
    .then(function(data) {
      $state.go('app.finish');
    }).catch(function(error) {
      $modal.open({ message: 'update failed', type: 'error' });
    });
} else {
  $comment.addComment(type, targetId, comment)
    .then(function(data) {
      $state.go('app.finish');
    }).catch(function(error) {
      $modal.open({ message: 'create failed', type: 'error' });
    });

after refactor

var postComment = function() {
  if (isEditMode) {
    return $comment.editComment(comment.id, comment);
  } else {
    return $comment.addComment(type, targetId, comment)
  }
}

postComment().then(function(data) {
  var goParams = {
    type: type,
    targetId: targetId
  }
  $state.go('app.finish', goParams);
}).catch(function(response) {
  $modal.open({ message: 'operation failed', type: 'error' });
});