简体   繁体   中英

Making synchronous Ajax calls from a loop via JQuery

I've got the loop below in my code and each iteration calls a function in which there's an Ajax call.

I'm trying to find a way to make each iteration run only after the former iteration completed.

Until now, as you can see, I've used a delay as a temporary solution.

Is there a neat way to make it synchronized?

Thanks!

$.each(matchIds, function(key,val){
        setTimeout(function(){
            gettingEvents(key, val,userID);
        },delay);
        delay+=1700;

    });

If they really are synchronous, then simply not using setTimeout will do the job.

$.each(matchIds, function(key,val){
    gettingEvents(key, val,userID);
});

This is, however, a terrible approach that will tie up the JS event loop while all the requests run. Use asynchronous requests instead. Iterate inside the success handler instead of in an each loop.

var match_id_keys = Object.keys(matchIds);
var i = 0;
get_next();

function get_next() {
    if (!match_id_keys[i]) {
        return;
    }
    var key = match_id_keys[i];
    var val = matchIds[key];
    $.ajax( ... ).done(function () {
        // Do stuff with data
        i++;
        get_next();
    });
}

In 2020, we now have decent browser support for async and await which are tools for managing promises, so this can be written as a simpler loop:

async function get_all_ids(matchIds) { const entries = Object.entries(matchIds); for (let i = 0; i < entries.length; i++) { const [key, val] = entries[i]; const data = await $.ajax(...); // Do stuff with data } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM