I've got an $.each loop, that is within another $.each that is calling a function to add values to my back end system.
My $.each loops are like this:
$.each(locations, function( i, location ) { 
    $.each(location, function( i, site ) {
        addsite ( site.url, site.address, site.zip, site.contact, site.id )
    })
})
When I call the function addsites directly, not from within the $.each loops it works as expected, however when called from within the $.each loops it works, but sometimes code is being called before other code has completed.
After lots of testing I've worked out it's due to $.ajax being called which obviously doesn't complete before the other code is run.
My working function is :
function addsite( url, address, zip, contact, id ) {
                
    // 1. lots of jquery
    // 2. lots of jquery
    
    $.ajax({ type: "POST",   
        url: url,
        cache: false,
        complete : function(text) {
            console.log ( '3.' + text )
        }
    });
    
    // 4. more jquery
})
I added debugging into points 1, 2, 3 and 4 and could see that everything in 1. and 2. is called correctly, but the code in 4. is being running before the $.ajax has completed.
When the function is called in the $.each loop, I see 1,2,4 multiple times in the console.log followed by multiple 3's as that is completing later. This needs to be running as 1,2,3,4.
I understand why that happens and have found adding async: false to $.ajax allows this to work, but that is depreciated so I'm trying to find a better way.
Do I need to do something to the $.each loops or the addsite function ? If it's the function I need to make sure this works when called directly not just from the $.each loops.
Could some advise how I can get this to work correctly.
Thanks
 
    