简体   繁体   中英

How return promise from multiple promises

I always in console see:

  1. teamsUpdated2
  2. addUserToProjects
  3. deleteUserFromProjects

but should bee in different order

var result = teamService.addOrDeleteUser(userId, newTeams, deleteTeams);
result.then(function () {
     console.log("teamsUpdated2");          
     });

function with multiple promises:

var _addOrDeleteUser = function (userId, addToProjects, removeFromProjects) {
    var deferred = $q.defer();
    var promises = [];

    promises.push(projectResource.addUserToProjects({ userId: userId }, addToProjects, function (result) {
        console.log("addUserToProjects");
        deferred.resolve();
        return result;
    }));

    promises.push(projectResource.deleteUserFromProjects({ userId: userId }, removeFromProjects, function (result) {
        console.log("deleteUserFromProjects");
        deferred.resolve();
        return result;
    }));

    return $q.all(promises);
}

You can use promise chaining for that -

travelService
       .getDeparture( user )                                           // Request #1
       .then( function( departure ){
            $scope.departure = departure;                            // Response Handler #1
            return travelService.getFlight( departure.flightID );       // Request #2
        })
        .then( function( flight ){
             $scope.flight = flight;                                // Response Handler #2
             return weatherService.getForecast( $scope.departure.date ); // Request #3
        })
        .then( function( weather ){
            $scope.weather = weather;                               // Response Handler #3
        });

For more reference see this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM