Reputation: 39
I don't know why this function is returning undefined. Please help me... Run Snippet
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
return (this.response);
}
});
xhr.open("GET", url);
xhr.send();
}
let arr = xhr('https://reqres.in/api/users?page=2');
console.log(arr);
Upvotes: 0
Views: 594
Reputation: 654
you trying to make async request, but expect that it will work in synchronous way.
The way you solve your problem is:
i recommend you to use promises instead of XMLHttpRequest. it's easy to understand and it's modern way to work with requests.
related links here: https://www.w3schools.com/js/js_callback.asp https://www.w3schools.com/js/js_async.asp
Upvotes: 0
Reputation: 2044
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');
Upvotes: 1