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);
}
});
}
count 3
count 3
count 3
- By default it jQuery uses the async request
- To check it code just visit https://codepen.io/anjaneyulubatta505/pen/gORWgOz and open the console and see the log statements.
- It will log the
count
as always3
as ajax executes asynchronously.
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);
}
});
}
count 0
count 1
count 2
async
to false
then jQuery executes the request synchronously how to wait for all asynchrous requests to complete?¶
- sometimes, we need to process a set of requests asynchronously and after execution of all requests we need to perform a specific functionality then we need to use [Promise])(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- Let's see an example to implement this scenario.
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: