0

I have 2 separate models which are populated by 2 different API calls. I do a fetch on them one-by-one and once both the model api calls are done and my view is available (then trigger deferred resolve), I have my view rendering logic i.e. write data to the view

Below is the code;

var myModel1 = new myModel1({
    attr1: attr1
});

var myModel2 = new myModel2({
    attr2: attr2
});

myModel1.fetch({
success: function() {
        myModel1Deferred.resolve(myModel1);
    }
});

myModel2.fetch({
success: function() {
        myModel2Deferred.resolve(myModel2);
    }
});


require(['view/my-view'], function(myView) {
    myViewDeferred.resolve(myView);
});

$.when(myModel1Deferred, myModel2Deferred, myViewDeferred).then(function(myModel1, myModel2, myView) {
    // My view rendering logic
}

Now the issue is that there are 2 separate cases (based on how the view is accessed):

  1. In the first case, I have both the model API calls...so in this case resolve would depend on myModel1Deferred + myModel2Deferred + myViewDeferred
  2. But in the 2nd case, I just need one model API call (i.e myModel1.fetch())...so in this case the resolve would depend only on myModel1Deferred + myViewDeferred

My question is should I have an if condition and write the $.when().then() separately for each condition OR can it be handled within a single $.then().when().

halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

0

You can pass an array of variable length to $.when by using apply. Something like

var promises = [
    myViewDeferred,
    myModel1Deferred
];
if (case#2)
    promises.push(myModel2Deferred);

$.when.apply($, promises).then(function(view) {
    view.render.apply(view, Array.prototype.slice.call(arguments, 1));
    // view.render(model1, [model2, …]);
});

Btw, instead of using many deferreds your fetch and require function should simply return promises, instead of accepting callbacks.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375