Angular Promises使用空数组

时间:2015-10-14 19:51:04

标签: angularjs angular-promise

我想要实现的目标是:

  • 调用我的服务以检索与医生相关的约会类型(未修复的类型数)中的所有约会
  • 如果有3种约会类型,则会有3次异步通话
  • 在所有3个承诺都已解决后,使用$ q.all()返回单个承诺

appointmentService

this.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {

        var promises = [];

        angular.forEach(appointmentTypeArray, function (appointmentType) {

            var defer = $q.defer();

            $http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
                .success(function (listOfAppointments) {

                    defer.resolve(listOfAppointments);
                    promises.push(defer.promise);

                });
        });

        return $q.all(promises);

    };

在我的控制台日志中,appointmentType返回[]。 发生这种情况是因为空洞的承诺'即使在进行3次异步调用之前,也会返回数组。我对承诺的概念还很陌生,最好的方法是什么?谢谢!

$scope.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {

    appointmentService.getAllDoctorAppointments(doctor, appointmentTypeArray)

        .then(function (appointmentType) {

//could take in any number. hardcoded 3 just for testing.
console.log(appointmentType)

            angular.forEach(appointmentType[0], function (xRay) {
                $scope.xRayAppts.events.push(xRay);
            });

            angular.forEach(appointmentType[1], function (ctScan) {
                $scope.ctScanAppts.events.push(ctScan);
            });

            angular.forEach(appointmentType[2], function (mri) {
                $scope.mriAppts.events.push(mri);
            });

        });

};

2 个答案:

答案 0 :(得分:1)

this.getAllDoctorAppointments = function (doctor, appointmentTypeArray) {
    var promises = [];

    angular.forEach(appointmentTypeArray, function (appointmentType) {

        promises.push($http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
            .success(function (listOfAppointments) {
                return listOfAppointments;
            });
        );
    });

    return $q.all(promises);
};

$http.get返回您想要收集的承诺,在这种情况下不需要新的延期。

答案 1 :(得分:0)

未将promise添加到数组中,因为将其添加到数组promises.push(defer.promise);的代码位于您尝试推迟的事物的结果代码中。因此,承诺不会被添加到承诺列表中,直到执行完毕后才会执行!

所以你可以在成功通话之外移动该推线看起来像这样:

angular.forEach(appointmentTypeArray, function (appointmentType) {

        var defer = $q.defer();

        $http.get('/appointments/?doctorName=' + doctor + '&apptType=' + appointmentType)
            .success(function (listOfAppointments) {

                defer.resolve(listOfAppointments);

            });
        promises.push(defer.promise);

    });

或者,您可以像lcycool建议的那样,直接将$http.get(...).success(...)调用直接添加到数组中。