在我的案例中如何解决我的承诺电话

How to resolve my promise calls in my case

我试图减少服务中的承诺对象。我有类似的东西

angular.module('myApp').service('testService', ['Employees','$q',
    function(Employees, $q) {
        var service = {};
        var firstEmp;

        var deferred = $q.defer();

        Employees.query({
            Id: 123
            }, function(objects) {
                firstEmp = objects[0];
                deferred.resolve(objects);
        })


        service.getFirstEmployee = function() {
             var deferredtwo = $q.defer();

            // return deferredtwo.promise;
            //How to solve the double promise defer in my case
            //First promise is wait for the whole employees
            //this one is to return first employee
            deferred.promise.then(function(){
                deferredtwo.resolve(firstEmp);
            })
            return deferredtwo.promise;
        }

        return service;
]);

控制器

testService.getFirstEmployee.then(function(firstEmployee){
    console.log(firstEmployee) <---show first employee
})

我不确定如何解决双重承诺对象。谁能帮我?非常感谢!

经过澄清我想这就是你想要的:

angular.module('myApp').service('testService', ['Employees','$q',
    function(Employees, $q) {
        var service = {};
        var deferred = $q.defer();

        Employees.query({Id: 123}, function(objects) {
            firstEmp = objects[0];
            deferred.resolve(objects);
        });

        service.getFirstEmployee = function() {
            return deferred.promise.then(function(employees){
                return employees[0];
            });
        }

        return service;
]);

如果您的最终 objective 只是为了获得第一个员工,那么您根本不需要所有这些 "double promise" 东西。只需与第一个员工达成一个承诺:

angular.module('myApp').service('testService', ['Employees','$q',
    function(Employees, $q) {

        var pFirstEmployee = $q(function (resolve) {
            Employees.query({ Id: 123 }, function(objects) {
                resolve(objects[0]);
            });
        });

        return {
            getFirstEmployee: function() {
                return pFirstEmployee;
            }
        };
    }
]);

如果您想要两种方法 - 一种是 returns 对从查询返回的所有员工的承诺,另一种是 returns 只是该组中的第一个,只需为所有人​​创建一个承诺员工和连锁店:

angular.module('myApp').service('testService', ['Employees','$q',
    function(Employees, $q) {

        var pAllEmployees = $q(function (resolve) {
            Employees.query({ Id: 123 }, resolve);
        }),
            pFirstEmployee = pAllEmployees.then(function (employees) {
            return employees[0];
        });

        return {
            getAllEmployees: function() {
                return pAllEmployees;
            },
            getFirstEmployee: function() {
                return pFirstEmployee;
            }
        };
    }
]);