davy
davy

Reputation: 4552

Return data from jQuery promise object

I am using $.getJSON() and trying to return data using various flavours of the code below:

 var changeUserPage = function (id) {
       return repository.getUserPage(id).done(function (data) {            
           // console.log(data)
       })
 }

The problem is that although inside the done function, I can see the correct data I want, I cannot return it to my calling function like:

 var data = dataContext.changeUserPage(lastPolicyWorkedOn);

data current holds the promise object:

Object {readyState: 1, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}

EDIT

The getJSON method looks like:

var getUserPage = function (policyId) {
       policyId = encodeURIComponent(policyId);

       var uri = "http://localhost:54997/api/policy/getUserPage/" + policyId;
       return $.getJSON(uri);         
}

How do I best return the actual json data?

Thanks

Davy

Upvotes: 1

Views: 3034

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

It won't be possible for changeUserPage to return the data, since the data is fetched using a async method $.getJSON.

Change

var data = dataContext.changeUserPage(lastPolicyWorkedOn);

to

dataContext.changeUserPage(lastPolicyWorkedOn).done(function(data){
    //do something with data
});

Upvotes: 2

Related Questions