多重承诺如何回报承诺

时间:2016-03-15 07:07:17

标签: javascript angularjs angular-promise

我总是在控制台看到:

  1. teamsUpdated2
  2. addUserToProjects
  3. deleteUserFromProjects
  4. 但应该按照不同的顺序

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

    具有多个承诺的功能:

    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);
    }
    

1 个答案:

答案 0 :(得分:2)

你可以使用promise chaining -

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
        });

有关详情,请参阅this