javascript wait for asynchronous callbacks

javascript wait for asynchronous callbacks

  • We use ajax calls very frequently on frontend applications.
  • One of most used javascript libraries for making the ajax calls is jQuery.
  • By using jQuery ajax we can make both synchronous and asynchronous calls.

how to make asynchronous ajax call with jQuery?

Let's see an example to make an api call with ajax

for (i = 0; i < 3; i++) {
  $.ajax({
    url: "https://reqres.in/api/users/2",
    dataType: "json",
    timeout: 500,
    success: function (data, status, xhr) {
      console.log("count", i);
    },
    error: function (jqXhr, textStatus, errorMessage) {
      console.log(jqXhr, textStatus, errorMessage);
    }
  });
}
output:
count 3
count 3
count 3

how to make synchronous ajax call with jQuery?

  • To make the synchronous ajax call we just need to pass the attribute async: true in the ajax call.
  • Let's modify the above example by adding the async to true.

for (i = 0; i < 3; i++) {
  $.ajax({
    url: "https://reqres.in/api/users/2",
    dataType: "json",
    async: false,
    timeout: 500,
    success: function (data, status, xhr) {
      console.log("count", i);
    },
    error: function (jqXhr, textStatus, errorMessage) {
      console.log(jqXhr, textStatus, errorMessage);
    }
  });
}
output:
count 0
count 1
count 2
- like above example when we pass async to false then jQuery executes the request synchronously

how to wait for all asynchrous requests to complete?

let promises = [];
for (i = 0; i < 3; i++) {
  promises.push(
    $.ajax({
        url: "https://reqres.in/api/users/2",
        dataType: "json",
        timeout: 500,
        success: function (data, status, xhr) {
        console.log("count", i, "random", Math.floor(Math.random() * 10));
        },
        error: function (jqXhr, textStatus, errorMessage) {
        console.log(jqXhr, textStatus, errorMessage);
        }
    })
  );
}
Promise.all(promises).then(function(){
    console.log("It's executing after all promises resolved. Hooray!")
})

output:

count 3 random 9
count 3 random 1
count 3 random 4
It's executing after all promises resolved. Hooray!
  • From the above code we can see that after executing the all asynchronous ajax calls our log statement executed.
  • jquery Ajax generates a promice when we do a ajax call.

References: