Home > OS >  How order Ajax call in loop
How order Ajax call in loop

Time:11-06

I use following codes to get data from a site, I get list of 330 categories. based on woocommerce rest api documentation this endpoint return just first 100 categories, so I have to use ?per_page= and &page= and put it in loop. my problem is that this code is not getting by order, sometimes it get last 30 then rest of 300, or first it get first 100 then 30 then 100 and rest. is this for async control in ajax? how order ajax calls in this loop?

for(let i=0; i <= 3; i  ){
    var get_cat_data = jQuery.get(url   '/wp-json/wc/v3/products/categories/?consumer_key='   ck   '&consumer_secret='   cs   '&per_page=100&page='   (i 1));
    get_cat_data.done(function(response_cat){
    console.log(response_cat);
        jQuery.each(response_cat, function(index, value){
            _cat_array.push(value.id   ':'   value.name);
        });
        jQuery('form.submit-new-product-data #form__categories').val(_cat_array);
    });
}

CodePudding user response:

Assuming your code is inside a function, make that function async ... then you can do this

for (let i=0; i <= 3; i  ){
    const response_cat = await jQuery.get(url   '/wp-json/wc/v3/products/categories/?consumer_key='   ck   '&consumer_secret='   cs   '&per_page=100&page='   (i 1));
    jQuery.each(response_cat, function(index, value){
        _cat_array.push(value.id   ':'   value.name);
    });
    jQuery('form.submit-new-product-data #form__categories').val(_cat_array);
}

You can also make the requests in parallel but process them in the correct sequence

const promises = [];
for (let i=0; i <= 3; i  ) {
    promises.push(jQuery.get(`${url}/wp-json/wc/v3/products/categories/?consumer_key=${ck}&consumer_secret=${cs}&per_page=100&page=%{i 1}`));
}
const results = await Promise.all(promises);
results.forEach(response_cat => {
    jQuery.each(response_cat, (index, {id, name}) => _cat_array.push(`${id}:${name}`));
}
jQuery('form.submit-new-product-data #form__categories').val(_cat_array);

and of course, if your code is not inside a function you could always wrap it in an async IIFE, to enable use of async/await

(async () => {
    // your code
})();
  • Related