如何通过内部的一个jQuery的Ajax请求环时, - 然后说明书? [英] How to loop through Ajax Requests inside a JQuery When - Then statment?

查看:158
本文介绍了如何通过内部的一个jQuery的Ajax请求环时, - 然后说明书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个API异步加载一组数据,当所有数据被加载我想触发所有的数据加载的事件。我遇到的问题是,我现在用的是API响应的对象数量限制为5次。我将可能需要检索30-40响应对象。

I am trying to load a bunch of data from an API Async and when all the data is loaded I want to trigger an event that all the data is loaded. The problem I am having is that the API I am using limits the number of response objects to five. And I would potentially need to retrieve 30-40 response objects.

所以,我想要做的就是创建一个当 - 那么语句循环槽数据项进行要求每五个项目,然后当所有的项目都装我想火加载的事件。我遇到的问题是,当,那么语句Ajax请求的成功之前完成。

So what I want to do is create a when - then statement that loops trough the data items and makes request for every five items then when all the items are loaded I want to fire a loaded event. The issue I am having is that the when-then statement is completing before the success of the ajax request.

到code我都试过了。

onto the code I have tried.

 function loadsLotsOfStats(stats, dataType, eventName, dataName, callback) {
     var groupedStats = [];
     while (stats.length > 0) {
         groupedStats.push(stats.splice(0, 5).join('/'));
     }
    j$.when(
        groupedStats.forEach(function (d) {
            loadJSONToData(model.apiUrl.replace("{IDS}", d), "json", "", dataName, function (d) { /*console.log(d);*/ }, true)
        })
    ).then(function () {
        j$(eventSource).trigger('dataLoaded', eventName);
    });

该loadJSONToData功能基本上只是一个包装功能的异步$阿贾克斯。

The loadJSONToData function is basically just a wrapper function for an Async $.ajax.

所以是该事件被触发得到实际加载数据之前。也由于某种原因,如果我试图通过一个语法错误,把循环就在时(语句呢?

so yeah the event is getting triggered before the data is actually loaded. Also for some reason if I try to put for loop right in the when( statement it through a syntax error?

有没有人对我怎么可以让一群Ajax请求的,等到他们都触发事件之前compeleted什么建议?或客场解决什么我现在有?

Does anyone have any advice on how I could make a bunch of Ajax requests and wait until they all are compeleted before triggering an event? Or a away to fix what I currently have?

在此先感谢您的帮助。

Thanks in advance for the help.

推荐答案

这是可以做到你的要求。但是,您要发送您的请求,可能是服务器有一个原因,他们执行的限制。正如有人谁的作品在网络发展,并亲眼目睹如何讨厌DDOS,原料药的拼抢,和其他虐待就可以了,我会建议符合他们的极限。

It's possible to do what you're asking. HOWEVER, the server you are sending your requests to probably has a reason for the limit they enforce. As someone who works in web development and has seen first hand how annoying DDOS, scraping, and other abuses of APIs can be, I would suggest conforming to their limit.

话虽这么说,这里是你如何能做到这一点。

That being said, here's how you can do it.

$。阿贾克斯居然会返回一个延迟的对象,所以你可以用它来你的优势。另外$。当可以接受任何数量的延迟对象。结合这两个事实可以解决你的问题。

$.ajax actually returns a deferred object, so you can use that to your advantage. Also $.when can accept any number of deferred objects. Combining these two facts can solve your problem.

var deferreds = [];
$.each(groupedStats, function(index, stat){
    deferreds.push(
        // No success handler - don't want to trigger the deferred object
        $.ajax({
            url: '/some/url',
            data: {stat: stat},
            type: 'POST'
        })
    );
});
// Can't pass a literal array, so use apply.
$.when.apply($, deferreds).then(function(){
    // Do your success stuff
}).fail(function(){
    // Probably want to catch failure
}).always(function(){
    // Or use always if you want to do the same thing
    // whether the call succeeds or fails
});

请注意,这不是一个竞争状态。虽然$就是异步的,$。每个不是,所以你deferreds的名单将在总榜单前你到$。当和$。这时/ $。失败/ $。永远只会触发一次他们都完成

Note that this is not a race condition. Although $.ajax is asynchronous, $.each is not, so your list of deferreds will be the total list before you get to $.when and $.then/$.fail/$.always will only be triggered once they all complete.

编辑:我忘了按5S添加的分裂,但是这说明了总体思路。你也许可以从这里弄清楚如何将其应用到您的问题。顺便说一句,你可以只使用array.splice(0,5),以获得未来5结果从阵列中。 .splice可以放心使用;如果元素的总数量小于5,它将只是所有剩余的元素。

I forgot to add the splitting by 5s, but this illustrates the general idea. You can probably figure out from here how to apply it to your problem. Incidentally, you could just use array.splice(0,5) to get the next 5 results from the array. .splice is safe to use; if the total number of elements is less than 5, it will just take all the remaining elements.

这篇关于如何通过内部的一个jQuery的Ajax请求环时, - 然后说明书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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