2016-03-15 120 views
0

我總是在控制檯看到如何回報承諾風趣h動車組承諾:從多個承諾

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

你能提供這兩種方法的內容,以及好嗎? 'projectResource.addUserToProjects'和'projectResource.deleteUserFromProjects' –

+1

另外,你的'deferred'似乎什麼都不做 - 你可以刪除'var deferred = $ q.defer();'和那兩個'deferred'的行。 resolve();' –

+0

你確定函數'addUserToProjects'和'deleteUserFromProjects'返回一個promise嗎?附: https://jsfiddle.net/hLk0oruy/ –

回答

2

您可以使用鏈接的承諾爲 -

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

+0

如果我正確地理解了這個問題,我認爲你的承諾鏈示例是正確的方法。 – stanleyxu2005

+0

正如我所理解的問題一樣,OP在想爲什麼「teamsUpdated2」首先被記錄下來,儘管在其他兩個承諾都解決後它應該被鏈接。 –

+0

謝謝@ stanleyxu2005 –