TeraTon
TeraTon

Reputation: 435

Backbone fetch, promises and if else. how do they work?

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

Answers (2)

Acatl Pacheco
Acatl Pacheco

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

Julio Menendez
Julio Menendez

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

Related Questions