0

I wrote this code below, it's pretty straightforward and what it dose is make a xhr request and then assign the response to a variable.

function myFunction(url){

  var myVariable;

  var myRequest = dojo.xhrGet({

      url: url,
      handleAs: "json"

  }).then(requestSucceeded, requestFailed);


  function requestSucceeded(response){

      myVariable = response;
      console.log('Value from the original response: ' + myVariable);
  }

  function requestFailed(error){

      console.log("Error: ", error.message);
  }   

  console.log('Value that will be returned to browser: ' + myVariable);
  return myVariable;
  
}

It works fine in Chrome, Firefox and IE 10, and I can see two messages from the console:

Value from the original response: some value

Value that will be returned to browser: some value

But issue comes when I run it in IE 9 or 8, it won't assign the response two the variable outside of the xhr object, I see two messages from the console like:

Value that will be returned to browser: undefined

Value from the original response: some value

I know it's caused by the non-blocking nature of JavaScript so the code keeps moving along even the response has not come to the callback yet, which made myVariable at the end of the code as undefined.

But what I can't understand is why it's working fine in Chrome and Firefox, why would Chrome wait till the response is received and then move along to execute rest of code.

So my question is how can I make it work in IE 9?

Thanks a lot!

Community
  • 1
  • 1
Vanni Zhang
  • 121
  • 3
  • I get `undefined` in all browsers -- that what I think it's supposed to do. See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Qantas 94 Heavy Jun 11 '14 at 05:09
  • What IE9+8 do, is actually what I would expect this script to do in all browsers. As you point out, you start an asynchronous call and that should not be finished before you return `myVariable` (thus it being `undefined`). Are you working in a local environment currently? Is your `url` local or online somewhere? Maybe the response is cached and thus returns immediately? – christian314159 Jun 11 '14 at 05:28
  • The first behavior you cite above is as if you set sync=true (see [the xhrGet docs](http://dojotoolkit.org/reference-guide/1.9/dojo/xhrGet.html)). Perhaps the first set of browsers fire the event immediately if they have the file cached? Try clearing your Chrome cache and see which behavior you get. – flamingcow Jun 11 '14 at 05:40
  • In addition to the question that @Qantas94Heavy linked to, if you're going to use deferreds (explained in the other answer), Dojo also has an implementation of it: http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html – g00glen00b Jun 11 '14 at 05:51

0 Answers0