Reputation: 31
DISCLAIMER - I've reviewed the existing SO entries and cobbled together something that should work but still does not.
I have the following function. Basically it is sending a pair of values to a webservice with the results coming back in JSON:
getPicklist: function () {
var xhrArgs = {
url: 'myUrl',
postData: dojo.toJson({
'opportunityId': 'myOppId',
'loggedInUserId': 'myUserId' //App.context.user.$key
}),
headers: {
"Content-Type": "application/json"
}
}
var deferred = dojo.xhrPost(xhrArgs);
deferred.then(
function (data) {
var jsonResponse = dojo.fromJson(data);
picklistName = jsonResponse.PicklistName;
if (!picklistName) {
picklistName = "defaultPickListName";
}
return picklistName;
},
function (error) {
alert("Could not load picklist " + error);
});
;
//return picklistName; -- null
}
My understanding after reading this: anonymous js function with xhrpost dojo not returning data
Was that adding a variable outside of this function scope, along with using dojo.deferred, would fix the issue. I tried placing a var outside of the function, and assigned the object to the picklistName variable.
However, I still cannot get this function's result (the picklistName variable).
Can someone please clarify what I am doing wrong, and how I can fix it?
EDIT - After making the changes Thomas Upton suggested, I am closer but I am getting a strange error.
I added the following function after getPicklist:
returnPicklistName: function () {
this.getPicklist().then(function (picklistName) {
return picklistName;
})
},
Because all I really want is the picklist (there's JSON that I want really but I will settle just for the picklist for now).
This throws the following error in Chrome dev tools - Uncaught TypeError: Object [object Object] has no method 'getPicklist'.
What else did I miss? Thanks.
Upvotes: 1
Views: 367
Reputation: 1899
Instead of returning picklistName
at the end of getPicklist
, you need to return a promise -- here, the result of then()
-- and add a callback that will receive the picklistName
when the deferred resolves.
getPicklist: function () {
// ...
var deferred = dojo.xhrPost(xhrArgs);
return deferred.then(
function(data) { /* get picklistName from data */ return picklistName; },
function(error) { /* ... */ }
);
}
Then, when you call getPicklist
:
this.getPicklist()
.then(function(picklistName) {
// Use picklistName here
});
Upvotes: 1