javascriptpromisechaining

What is the difference between these two syntax


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 ?


Solution

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

    Yes, because you're branching the promise chains:

                  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.