Angular Promises 返回带有空数组的 q.all( )

Angular Promises returning q.all( ) with empty array

我想达到的目标是这样的:

约会服务

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

    };

在我的控制台日志中,约会类型 returns [ ]。 发生这种情况是因为空 'promises' 数组甚至在进行 3 个异步调用之前就被 returned。我对承诺的概念还是很陌生,解决这个问题的最佳方法是什么?谢谢!

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

        });

};
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 returns 你想要收集的承诺,在这种情况下不需要新的延迟。

promise 没有被添加到数组中,因为将它添加到数组 promises.push(defer.promise); 的代码在您试图延迟的结果代码中。因此,在执行之前,promise 不会被添加到要执行的 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(...) 调用添加到数组中。