wait for ajax to finish javascript code example

Example 1: jquery wait for all ajax requests to complete

//jQuery waiting for all ajax calls to complete b4 running
$.when(ajaxCall1(), ajaxCall2()).done(function(ajax1Results,ajax2Results){
    //this code is executed when all ajax calls are done
});

function ajaxCall1() {
    return  $.ajax({
        url: "some_url.php",
        success: function(result){
            console.log(result); 
        }
    });
}   

function ajaxCall2() {
    return  $.ajax({
        url: "some_url.php",
        success: function(result){
            console.log(result); 
        }
    });
}

Example 2: wait for ajax to finish

function functABC() {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: 'myPage.php',
      data: {id: id},
      success: function(data) {
        resolve(data) // Resolve promise and go to then()
      },
      error: function(err) {
        reject(err) // Reject the promise and go to catch()
      }
    });
  });
}

functABC().then(function(data) {
  // Run this when your request was successful
  console.log(data)
}).catch(function(err) {
  // Run this when promise was rejected via reject()
  console.log(err)
})

Example 3: how to wait till jquery post request has been made

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}