仅在所有AJAX调用完成后如何执行? [英] How to execute only after all AJAXcalls are made?

查看:50
本文介绍了仅在所有AJAX调用完成后如何执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,函数 getPollById 取决于 responselength 而被调用,因此对于每个响应,API都会调用一次以访问数据.使用 $ q.all ,执行完所有命令后,我将无法执行.那么,在完成所有调用后如何执行?我在这里犯什么错误?我在第一个功能后得到consoled.log.我想要在 getPollById 完成对整个 response.length 的请求之后.我该怎么办?

As you can see function getPollById is called depending on the responselength, so for every response, the API makes a call to access the data. Using $q.all, I am unable to execute after everything has been executed. So how do I execute after all calls are made? What mistake am I making here? I am getting the consoled.log after the first function. I want after the getPollById finished requesting for the entire response.length. How do I do it ?

adminApp.controller('PollController', function($scope,$window,$timeout, $rootScope,$routeParams, $http, $location, $q ) {
    displayLoader("Loading...", "100px");
    var httpData1 = $http({
        method: 'get',
        url: "the url",
    }).
    success(function(response) {
        $scope.poll = response;            
        for (var i =  0; i < response.length; i++) {
            getPollById(response[i], i);
            angular.element('#loadering').fadeOut('slow');
        }
    }).
    error(function(response) {
        console.log(response || "Request failed");
    });
    var httpData2;

    function getPollById(i, index){
        httpData2 =  $http({
            method: 'post',
            url:  BASE_URL+'admin_api/admin_poll_api/admin_poll/',
            data: i
        }).
        success(function(response) {
            appendData(response, index);
            var labels = [];
            var data = [];
            for (var i = 0; i < response.response.options.length; i++) {    
                labels.push(response.response.options[i].options);
                data.push(response.response.options[i].votes);
            }
        }). 
        error(function(response) {
            console.log(response || "Request failed");
        });
    }

    $scope.polls=[];
    function appendData(response, index){
        $scope.polls[index] = response;
    }
    $q.all([httpData1, httpData2]).then(function() {
        console.log("all calls have finished ");
    })  
});

推荐答案

请记住,$ q.all将在第一次拒绝后退出,如果您要确保所有承诺均已结束(已解决或被拒绝),则可以使用角度承诺附加模块( https://github.com/ohjames/angular-promise-extras)其$ q.allSettled方法.因此,您可以将pwolaq不错的答案中的$ q.all()替换为:

keep in mind that $q.all will exit after first reject, if you want to be sure that all promises ended (resolved or rejected), you may use angular promise extras module (https://github.com/ohjames/angular-promise-extras) whith its $q.allSettled method. So you can just replace $q.all() in pwolaq's nice answer with:

$q.allSettled (promises);

这篇关于仅在所有AJAX调用完成后如何执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆