0

I have a Cross Platform request call, and it gets the data inside the xhr.onload function, how do I return that data to the main function?

makeCorsRequest(email) {
    var xhr = this.createCORSRequest(email);
    xhr.send()      
    xhr.onload = function() {
       var text = xhr.responseText;
       return text //I want to return this on the makeCorsRequest function after the .send() is done
     };

}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Gustavo
  • 874
  • 4
  • 13
  • 27

2 Answers2

0

Short answer - you can't. Xhr request are asynchronous - the makeCorsRequest will end without waiting for the request to be finished, and onload will be execute alone when the request ends.

You need to use response data inside the onload function, or give it a callback function to be executed.

Dionei Miodutzki
  • 657
  • 7
  • 16
0

You cant. onload accepts a callback to execute it after a server response has arrived. XHR uses the callback to not block main thread of the application and allow rest of the code to be executed. Otherwise, a page would be frozen everytime it was making a request to the server.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166