0

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);

2 Answers 2

1

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');

Sign up to request clarification or add additional context in comments.

Comments

0

you trying to make async request, but expect that it will work in synchronous way.

The way you solve your problem is:

  • use callbacks
  • use promises
  • use async/await (that's just wrapper of of promises)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.