What is the difference between these two syntax

一世执手 提交于 2019-12-20 05:38:54

问题


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.



来源:https://stackoverflow.com/questions/29210234/what-is-the-difference-between-these-two-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!