推迟 return 工厂直到循环完全完成 angularjs

Defer return of factory until loop is completely finished angularjs

我正在尝试创建一个方法,在从 API 中获取对象后,return 是一个对象数组。问题是来自工厂的 return 发生在所有调用完成之前。我已尝试使用 $q.defer,但它仍会在准备发货之前发送 return。 这是我到目前为止想出的。

angular.module('watchList').factory('storageService', ['$http', '$q', function ($http, $q) {
storage = {};

storage.getMovies = function () {

    var movies = localStorage.getItem('movies');
    var movieArray = angular.fromJson(movies);
    var newArray = [];
    var defer = $q.defer();

    angular.forEach(movieArray, function (id) {
            newArray.push($http.get(api + id));
    });
    $q.all(newArray).then(function (response) {
            defer.resolve(response);
     });

    return defer.promise;
}

这是我尝试从中发出呼叫的控制器

angular.module('watchList').controller('watchListController', ['$scope', 'storageService', function ($scope, storageService) {
$scope.movies = storageService.getMovies();

我希望循环在 return 数组之前完成所有操作。

getMovies 将return 立即承诺。您需要使用 "then" 来等待该承诺。

$scope.movies = storageService.getMovies().then((response) => ...)

您不需要创建承诺,您可以 return 通过 $q.all(newArray) 调用 return 的承诺。

问题是当结果只能异步可用时,您不能指望同步获得结果。所以你需要继续使用 then:

storage.getMovies = function () {
    var movies = localStorage.getItem('movies');
    var movieArray = angular.fromJson(movies);
    var newArray = movieArray.map(function (id) {
        return $http.get(api + id);
    });
    return $q.all(newArray);
}

storageService.getMovies().then(function(movies) {
    $scope.movies = movies;
    // ... other code working with $scope.movies 
});

旁注:map 方法执行与 forEach 相同的操作,但立即 return 数组,这非常实用。