Reputation: 1141
I wrote a function to retrieve all the data for various arias like this..
function retrieveData(dom_sclapi) {
var apiResponse;
dojo.xhrGet({
url : dom_sclapi,
handleAs: handle,
//sync: true,
headers: { "Accept": "application/json" },
preventCache: true,
//Success
load: function(Response) {
apiResponse = Response;
},
// Ooops! Error!
error: function(Error, ioArgs) {
//apiResponse = Error;
//console.log(ioArgs.xhr.status);
}
});
//apiResponse
return apiResponse;
}
But apiResponse returns an undefined on sync = false state (here when i comment the sync attrribute). Its returns correct data output on sync = true only. So this makes problem on chrome and IE in loading styles as the chrome and IE blocks all other actions on synchronous calls.
How can I overcome this situation ? What is the actual problem with my code?
Upvotes: 0
Views: 2631
Reputation: 408
You need to better grasp the idea behind sync and async code.
That is exactly the case it returns undefined
, because it isn't synchronized and value isn't available yet.
When you set as synchronized, the rest code execution will wait for function return, otherwise you let code continue without waiting for result.
When you're writing asynchronous code, you shouldn't expect it to return a value on the next line of code, as it will most likely wont.
Instead you should create an event or a callback when return value becomes available.
The load:
in this case is a callback, when request recieved response.
Also refer to documentation regarding Deferred objects. They're also described in xhrGet
Thus your code above may become something like this.
function retrieveData(dom_sclapi, callback) {
// Will return Deferred object
return dojo.xhrGet({
url : dom_sclapi,
headers: { "Accept": "application/json" },
preventCache: true,
// Pass callback function to do something with response
load: callback,
error: function(Error, ioArgs) {
//console.log(ioArgs.xhr.status);
}
});
}
// Or get data by deferred object
retrieveData(url, null).then(function(Response){ /* Do something with response */ })
// Via callback
retrieveData(url, function(Response){ /* Do something with response */ });
Upvotes: 3