Reputation: 435
I have a problem that I'm not sure how to solve smartly in my backbone app. I have a view that requires either 2 or 3 different models to be fetched.
I have a profile view, that shows a customer his tasks and profile info, but when the coach accesses it, i also want to load the coaches model to enable the coach to switch stuff around.
How do promises behave with if else statements? Can I write the code in the way I have written and does it work that way?
var tasks = new App.Task.Collections.Tasks();
var coaches = new App.Coach.Collections.Coaches();
var user = new App.User.Models.User();
if(App.User.Models.currentUser.isCoach()){
var userPromise = user.fetch();
var coachPromise = coaches.fetch();
var tasksPromise = tasks.fetch({
data: {
userId: userdId
}
});
$.when(userPromise, coachPromise, tasksPromise).then(function(){
App.Layout.page.show(layout);
});
}else{
var userPromise = user.fetch();
var tasksPromise = tasks.fetch({
data: {
userId: userdId
}
});
$.when(userPromise, tasksPromise).then(function(){
App.Layout.page.show(layout);
});
}
How do promises work with if else statements?
Upvotes: 2
Views: 1751
Reputation: 3
you may collect your promises on an Array and then pass them to $.when
var promises = [];
promises.push( modelA.fetch() ); // default
if(value){
promises.push( modelB.fetch() ); // conditionally added
}
$.when.apply($, promises).then(function(){
// do your stuff
});
Upvotes: 0
Reputation: 471
Your code looks correct. The if/else statements in your code won't affect at all the promises because you have all the .fetch()
calls in their corresponding blocks. Just remember to pass all those collections to the layout you are showing.
Upvotes: 1