This is very very simple, Maybe you're new to Javascript, If you are not aware Js is an asynchronous
language, it means that it would not block or wait for any function to complete which might be time consuming ( in this case a request to the server), This helps it to process other things meanwhile the request is taking place.
So in your case, it's creating the request to the server, but at the same time continues to execute your function and return the default value, i.e undefined
, You can pass a callback
to be called when the request is completed.
function callWhenFinished(arr) {
console.log(arr);
}
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function() {
if (this.readyState === this.DONE) {
callWhenFinished(this.response); // callback
}
});
xhr.open("GET", url);
xhr.send();
}
xhr('https://reqres.in/api/users?page=2');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…