带有$ q.all的嵌套承诺的$ q.all

时间:2015-11-01 21:10:26

标签: javascript angularjs promise angular-promise angularjs-http

以下函数尝试返回仅在所有异步HTTP调用完成时解析的promise:

$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中的承诺尚未得到解决,第二个承诺($q.all([promise1, promise2]))也会解决。

1 个答案:

答案 0 :(得分:1)

因为您没有创建promise数组,实际上它包含$ q.defer()对象。你应该使用

promises.push(newPromise.promise);

而不是

promises.push(newPromise);

此外,您需要避免使用这些反模式,因为您正在不必要地创建$q对象,因为您有从$http.get返回的承诺对象。

<强>代码

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