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.

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler