$q.all with nested promise also created with $q.all

$q.all with nested promise also created with $q.all

以下函数尝试 return 只有在所有异步 HTTP 调用完成后才会解析的承诺:

$scope.saveThat = function () {
    var promises = [];

    for (var i = 0; i < array.length; i++) {
        var newPromise = $q.defer();
        promises.push(newPromise);

        // some more code...

        (function (i, newPromise) {
            $http(httpData)
                .success(function (response) {
                    newPromise.resolve('Success');
                })
                .error(function (response) {
                    newPromise.reject('Error');
                });
        })(i, newPromise);

    }
    return $q.all(promises);
};

下面的代码片段调用了这个函数。

// save this...
var promise1 = $rootScope.saveThis(result.Person);
promise1.then(function (success) {
    }, function (error) {
        saveErrorMessage += 'Error saving this: ' + error + '.';
    });

// save that...
var promise2 = $rootScope.saveThat(result.Person);
promise3.then(function (success) {
    }, function (error) {
        saveErrorMessage += 'Error saving that: ' + error + '.';
    });

// wait until all promises resolve
$q.all([promise1, promise2])
.then(
    function (success) {
        $scope.$emit(alertEvent.alert, { messages: 'Saved successfully!', alertType: alertEvent.type.success, close: true });
    }, function (error) {
        $scope.$emit(alertEvent.alert, { messages: saveErrorMessage, alertType: alertEvent.type.danger });
    });

我遇到的问题是,即使 promise2 中的 promise 尚未解决,第二个 promise ($q.all([promise1, promise2])) 也会解决。

因为你不是在创建一个promise的数组,实际上它包含一个$q.defer()对象。你应该使用

promises.push(newPromise.promise);

而不是

promises.push(newPromise);

您还需要避免那些反模式,因为您不必要地创建了 $q 对象,因为那里有从 $http.get.

返回的 promise 对象

代码

$scope.saveThat = function() {
    var promises = [];
    for (var i = 0; i < array.length; i++) {
      // some more code...
      var promise = $http(httpData)
        .then(function(response) {
          return 'Success'; //returning data from success resolves that promise with data
        }, function(response) {
          return 'Error'; //returning data from error reject that promise with data
        });
      promises.push(promise); //creating promise array
    }
    return $q.all(promises); //apply $q.all on promise array
};