Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - How to loop through Ajax Requests inside a JQuery When - Then statment?

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.

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.

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);
    });

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

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.

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...