Reputation: 440
I am trying to use a series of requests to build a model before binding it to my view. I am having a hard time understanding how I can leverage the response of one request to make the next request. My issue is that my "sponsor" and "manager" properties resolve as a promise and not the response.
$.get("/projects/1") .then(function(data){ var manager = $.get("/employees/" + data.ProjectManagerId); data.manager = manager; return data; }) .then(function(data){ var sponsor = $.get("/employees/" + data.ProjectSponsorId); data.sponsor = sponsor; return data; }) .then(function(data){ //Bind data to view //data.manager is a promise //data.sponsor is a promise }) .done();
How can I ensure the data is returned instead of the promise?
Upvotes: 0
Views: 64
Reputation: 57723
It looks to me like the manager and sponsor requests can be paralellized (executed simultaneously).
I'd slap a when
in there:
$.get("/projects/1")
.then(function(data){
var manager_req = $.get("/employees/" + data.ProjectManagerId);
var sponsor_req = $.get("/employees/" + data.ProjectSponsorId);
return $.when(data, manager_req, sponsor_req);
})
.then(function(data, manager, sponsor){
data.sponsor = sponsor;
data.manager = manager;
return data;
})
.done(function(data){
//Bind data to view
//data.manager is resolved
//data.sponsor is resolved
});
Nesting the when promise deals a little bit better with data
:
$.get("/projects/1")
.then(function(data){
var manager_req = $.get("/employees/" + data.ProjectManagerId);
var sponsor_req = $.get("/employees/" + data.ProjectSponsorId);
return $.when(manager_req, sponsor_req).then(function(manager, sponsor){
data.sponsor = sponsor;
data.manager = manager;
return data;
});
})
.done(function(data){
//Bind data to view
//data.manager is resolved
//data.sponsor is resolved
});
Upvotes: 1