Skip to content

Instantly share code, notes, and snippets.

@sufian07
Forked from geowulf/FlattenedPromiseChain.md
Created July 20, 2018 10:32
Show Gist options
  • Save sufian07/b509e136d6eeb13698ba03866d8c9444 to your computer and use it in GitHub Desktop.
Save sufian07/b509e136d6eeb13698ba03866d8c9444 to your computer and use it in GitHub Desktop.
Promises: Flattened Promise Chain

Credit: Thomas Burleson

Since promise handlers can return Promises, let’s use that technique to refactor an implementation:

var Dashboard = function( $scope, user, ServiceOne, ServiceTwo )
    {
        Service-1
            .getAddressInfo( user )                                              // Request #1
            .then( function( address )
            {
                $scope.address = address;                                       // Response Handler #1
                return ServiceOne.getPhoneInfo( address.userID );                // Request #2
            })
            .then( function( phoneInfo )
            {
                $scope.phoneInfo = phoneInfo;                                    // Response Handler #2
                return ServiceTwo.getAccountInfo( $scope.address.userID );        // Request #3
            })
            .then( function( accountInfo )
            {
                $scope.accountInfo = accountInfo;                                // Response Handler #3
            });
#
        $scope.flight     = null;
        $scope.planStatus = null;
        $scope.forecast   = null;
    };

The important change here is to notice that the response handler returns a Promise. See how the handler for getAddressInfo() returns a promise for getPhoneInfo()? And the success handler for getPhoneInfo() which returns a promise for getAccountInfo().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment