【问题标题】:Nested $http calls $q.all returns promises but not resolved嵌套的 $http 调用 $q.all 返回承诺但未解决
【发布时间】:2015-05-19 20:57:50
【问题描述】:

我调用了一个函数,该函数返回一个带有我想在链式调用中使用的 ID 的列表。在我想读取所有返回的对象之前,一切似乎都有效。这些都是承诺,但我不知道为什么我无法解决它们。

        //Get bubbles and then it calls another function getBubbleMessage with result from previous and last getBubbleMessage returns an array of promises. 

   $scope.loadStartPage = function () {

        $scope.getBubblesThatUserHasAccessTo().then($scope.getBubbleMessage).then(function (data) {
            $log.info("INFO:: " + data);
            $scope.bubblesWithMessages = data;


        });
    };

    $scope.getBubblesThatUserHasAccessTo = function () {
        var deferred = $q.defer();

        BubblesService.getBubblesUserAccess().then(function (result) {
            deferred.resolve(result);

        });

        return deferred.promise;
    };

这个函数正在获取一些我们需要的东西来解析连接到上面服务返回的那些 id:s 的消息

    $scope.getBubblesThatUserHasAccessTo = function () {
        var deferred = $q.defer();

        BubblesService.getBubblesUserAccess().then(function (result) {
            deferred.resolve(result);

        });

        return deferred.promise;
    };

此函数获取所有消息并返回承诺对象 - 这些我无法解决??

    $scope.getBubbleMessage = function (data) {

        var deferred = $q.defer();
        var promises = [];

        angular.forEach(data, function (item) {
            $log.info("DDD" + item.name);
            var promise = BubblesService.getBubbleMessages(item.id, 0, 1);
            promises.push(promise);
        });

        //return $q.all([promises]);
        $q.all([promises]).then(function (result) {
            $log.info(result);
            return result[0];

        });

    };

上面的函数返回一个包含 60 个对象的数组。

最后,我想在页面上的 ng-repeat 中使用一个新对象。我真的认为这是我对角度和承诺的新手....但是在尝试解决这个问题几个小时后我真的需要帮助:)

【问题讨论】:

  • 应该是return $q.all([promises]);

标签: javascript angularjs promise q


【解决方案1】:

$q.all 接受一个 promise 数组。在这里,您正在执行 $q.all([myPromises]),它会立即解决,因为 '[myPromise]' 是一个数组而不是一个承诺(当你给一个数组参数时,第一个且唯一的元素是一个承诺数组应该简单地使用promise数组。所以[]而不是[[]])。第二个问题:您没有在父函数中返回此承诺。

你应该简单地改变块

$q.all([promises]).then(function (result) {
            $log.info(result);
            return result[0];

        });

return $q.all(promises);

对于数组中的每个 Promise,将使用一组已解析的数组进行解析。

【讨论】:

  • 我试过了,它似乎可以工作,但我无法理解之后如何访问这些对象。在我的方法中。我怎样才能看到它们的结构? $scope.bubblesWithMessages = 数据; ??有没有办法查看数据的样子?
  • 只需 $scope.bubblesWithMessages = 数据;是的,数据是一个消息数组
  • console.log(data) ? {{bubblesWithMessages | json}} ?你到底是什么意思?
  • 我做了一个 JSON.stringify på 数据对象并得到了这个。 [[{"$$state":{"status":0}},{"$$state":{"status":0}},{"$$state":{"status":0}}, {"$$state":{"status":0}},{"$$state":{"status":0}},{"$$state":{"status":0}},跨度>
  • 你能显示你的 BubblesService.getBubbleMessages 方法的内容吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
  • 2015-06-23
  • 1970-01-01
相关资源
最近更新 更多