Q
Q
Quintis2021-04-21 11:16:05
AJAX
Quintis, 2021-04-21 11:16:05

How to pass data asynchronously with XMLHttpRequest?

How to pass value from XMLHttpRequest request to this.VideoUrl class variable when asynchronous ?

class Test{
  constructor() {
    this.VideoUrl = "";
    this.url = "https"
  }
  getUrl(){
    let xhr = new XMLHttpRequest();

    xhr.open("GET", this.url, true);

    xhr.send();

    let transfer =(x)=>{
      this.urlToVideo = x;
    }

    function handler() {
      let VideoUrl = this.responseXML
      transfer(VideoUrl);
    }
    
    
    xhr.onload = handler;

  }
  log(){
    console.log(this.urlToVideo)
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-04-21
@Quintis

Quintis , Here, purely at random, you are trying to do something like this?

test.getUrl()
test.log()

If yes, then it won't work. Because the order of execution is as follows:
  1. call to getUrl
  2. Start sending a request
  3. Assigning an onload handler
  4. call log
  5. Expectation ...
  6. Returning a response from the server
  7. call transfer

You need a mechanism to call log AFTER the request has returned. For example promise or callback

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question