weixin_33709590 2016-04-18 12:12 采纳率: 0%
浏览 65

循环中有多个AJAX调用

I need a way to send multiple AJAX calls at the same time in Javascript/Angular. After some searching i couldn't find an answer. What i want to do is send all my requests as fast as possible. If i execute my calls in a for loop or in a queue of promises with the $q library in Angular, a request gets sent, waits for it to execute the callback, and then sends the next one. This is a example code:

var array = [];
    Page.get({id:1}, function(result){
        for(var i = 0; i < result.region[0].hotspots.length; i++){
            var promise = Hotspot.get({id: result.region[0].hotspots[i].id});
            array.push(promise);
        }
        $q.all(array).then(function(data){
            console.log(data);
        });
    });

Page is a angular resource with a get method which requires a ID.

What i want is that they all get sent at the same time and they call their callback when ready. The order in which the calls get returned doesn't really matter.

Thanks

  • 写回答

3条回答 默认 最新

  • weixin_33719619 2016-04-18 12:26
    关注

    Think outside the box with Web Workers

    An interesting aproach to solve this question, is to use web workers to execute the requests in a different thread. if you are not familiar with web workers i advice you to start by this great tutorial of techsith. Basically, you will be able to execute multiple jobs at the same time. See also the W3Schools Documentation.

    enter image description here

    This article from Html5Rocks teach us how to use Web Workers without a separate script file.

    评论

报告相同问题?