What is the diference between these two syntax

2019-03-06 14:31发布

问题:

If i have

promise = userService.updateUser($stateParams.userId, req);

promise.then(
    function(user) {
        logger.logSuccess('Updated user');
        $scope.resetForm();
        WizardHandler.wizard().goTo(0);
        return user;
    }, 
    function(error) {
        logger.logError('Ups an error has occurred');
        console.error('error updating user: ' + error);
    }
); 

promise.then(function(user) {
    _.each(uploader.getNotUploadedItems(), function(item) {
        return item.formData.push({
            id: user.id
        });
    });
});

Then if the updateUser fails the log will be shown and then second then will not be executed however if i have

promise = userService.updateUser($stateParams.userId, req).then(
    function(user) {
        logger.logSuccess('Updated user');
        $scope.resetForm();
        WizardHandler.wizard().goTo(0);
        return user;
    }, 
    function(error) {
        logger.logError('Ups an error has occurred');
        console.error('error updating user: ' + error);
    }
); 

promise.then(function(user) {
    _.each(uploader.getNotUploadedItems(), function(item) {
        return item.formData.push({
            id: user.id
        });
    });
});

The second then will be executed

I can't figure out why, i mean isn't this just regular chaining ?

回答1:

if the updateUser fails the log will be shown and then second then will not be executed

Yes, because you're branching:

              success: - logSuccessAndResetForm()
               |       - makeNewFormData()
updateUser() --+
  promise      |
              error    - logError()

but when using regular chaining the second chain will be executed

Yes, of course. Your error handler handles the error and the promise is fulfilled with the return value.

              success: - logSuccessAndResetForm()           success: - makeNewFormData()
               |                               \             |
updateUser() --+                                >- promise --+
               |                               /             |
              error    - logError()           ´             error:   (nothing)

See also this answer for prettier control flow diagrams of similar code.