I have 2 function that should be called when the page is loading.
window.addEventListener("load", function(e) {
func_a(); //send request to server (Node js)
func_b(); //send request to server (Node js)
});
func_a
will send to the server a request which just update list and will not return by .end
.
func_b() should send a request to the server and notify to all responses in the list.
But, for some reason the request of func_b()
sent before the another request.. and notify nothing actually.
Why is it happening?
Edit:
function func_a() {
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', function (e) {
if(xhttp.status != 200){
//handle error
return;
}
handle_func(this.responseText);
func_a();
});
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Ajax works asynchronously, so It is not guaranteed to complete the first request before the second one. So you have to make the second request after the first one is finished by providing it as a callback function for the first request
function func_a(callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback();
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
function func_b() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Do something here
}
};
xhttp.open("GET", "ajax_info2.txt", true);
xhttp.send();
}
func_a(func_b);
Using Promise
is fair enough if you want something like :
func_a().then(() => {
console.log('Hi I am callback of func_a');
func_b().then(() => {
console.log('Hi i am callback of func_b')
})
})
If so & you love this paradigm , then, your functions should be rectified to return promises :
function func_a() {
return new Promise((resolve, reject) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve();
} else {
reject()
}
};
xhttp.open('GET', 'ajax_info.txt', true);
xhttp.send();
});
}
function func_b() {
return new Promise((resolve, reject) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve();
} else {
reject()
}
};
xhttp.open('GET', 'ajax_info2.txt', true);
xhttp.send();
});
}
Note : Preparing functions to return promise is a ground for async-await
if you are familiar with ES7 :
async function myCalls() {
await func_a();
func_b();
}
myCalls();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.