vannizhang@gmail.com

How do I assign the esriRequest response to a variable

Discussion created by vannizhang@gmail.com on Jun 10, 2014
Latest reply on Jun 12, 2014 by vannizhang@gmail.com
Hi guys,

I have the code below, it's pretty straightforward and what it dose is making an esriRequest and then assign the serviceDescription of a Feature Layer from the response to a variable.

function getFeatureServerDescription(url){

    var serviceDescriptionStr;

    require(["esri/request"], function(esriRequest) {
          var layersRequest = esriRequest({
            url: url,
            content: { f: "json" },
            handleAs: "json",
            sync: true,
            callbackParamName: "callback"
          });
          
          layersRequest.then(requestSucceeded, requestFailed);
    });

    function requestSucceeded(response){

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

    function requestFailed(error){

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

    }   

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


It works fine in Chrome, Firefox and IE 10, the service description is returned 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 esri request 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!

Outcomes