Reputation: 51
Consider this code, just like a toy example:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
Let's consider that there are five kinds of asynchronous calls inside the function loadDoc()
. What I want to do is now is to call another function or any piece of code when all five callback functions are executed. Does Javascript provide anything to help with this situation, or we need to set a flag to check if all 5 tasks are executed?
Upvotes: 2
Views: 189
Reputation: 2460
You can either use a callback or a promise,
callback example:
function loadDoc(cb) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
cb(xhttp.responseText); // <= run the callback
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc(function(res) {
console.log(res);
// do something
});
promise example:
function loadDoc(cb) {
return return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
resolve(xhttp.responseText); // <= run the callback
} else {
reject(xhttp.responseText);
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc()
.then(function(res) {
console.log(res);
// do something
})
.catch(function(err) {
console.error(err);
// do something
});
Upvotes: 0
Reputation: 3811
If you use promises you'll be able to use Promise.all([promises])
.
"Promisifying" your current ajax request:
function loadDoc() {
req().then(function (responseText) {
document.getElementById("demo").innerHTML = responseText;
})
}
function req () {
return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
} else {
reject();
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
});
}
Upvotes: 2