1

Let's consider we have a file named hello.txt, and its content is :

Hello World !

We have a constant res, which is defined as :

const res = AJAXResponse("hello.txt")

So, far I defined AJAXResponse() as :

const AJAXResponse = (src) => {
  var request = new XMLHttpRequest();
  request.open('GET', src, true);

  request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // Success!
    var resp = this.response;
  } else {
   // We reached our target server, but it returned an error
  }
}

request.onerror = function() {
 // There was a connection error of some sort
}

request.send()

}

This works preety fine but I am not able to attach the data in this.response to the res constant. I want the output to be something like this :

const res = "Hello World !" // As returned by the function

But, I don't know how to do it. Can you help me with that ?

Debarchito
  • 1,305
  • 7
  • 20
  • 1
    Due to javascript nature, you can't, unless you use `async` – ariel Mar 31 '20 at 04:53
  • @ariel So, if I replace the boolean true with false, and make the call sync..., then will it work ? – Debarchito Mar 31 '20 at 04:55
  • 1
    Maybe, but you shouldn't. I was talking about `async`/`await` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – ariel Mar 31 '20 at 05:17

0 Answers0