This is our code inside a single function. I'm just beginning to get better with BackboneJS.
// let's pull desktop data
this.desktop = new desktopItemModel({device: 'desktop'});
this.desktopPromise = this.desktop.fetch();
// let's pull mobile data
this.mobile = new mobileItemModel({device: 'mobile'});
this.mobilePromise = this.mobile.fetch();
// I'm not sure if the previous developer was trying to implement similar to $q.all
this.allPromise = [desktopPromise, mobilePromise];
$.when(this.desktopPromise).done(_.bind(function() {
// do your desktop stuff
}, this));
$.when(this.mobilePromise).done(_.bind(function() {
// do your mobile stuff
}, this));
if (this.allPromise) {
$.when.apply($, this.allPromise).done(_.bind(function() {
// do your stuff here if desktop
....
// do your stuff here if mobile
....
}, this));
}
I noticed that there are times that our data in our variable gets mixed up between desktop and mobile. The response from the api server is fine. I actually suspected that the API team was returning us wrong data until I debugged our app, it was our code that was doing something weird.
How can this be refactored so that data doesn't get mixed up? Someone told me in irc, "promises have weird behaviors".
Let's rewrite this a little
this.desktop = new desktopItemModel({device: 'desktop'});
this.desktopPromise = this.desktop.fetch()
.then(function(){
// do your desktop stuff
}.bind(this));
this.mobile = new mobileItemModel({device: 'mobile'});
this.mobilePromise = this.mobile.fetch()
.then(function(){
// do your mobile stuff
}.bind(this))
$.when(this.desktopPromise, this.mobilePromise)
.done(function() {
// do your stuff here if desktop
// do your stuff here if mobile
}.bind(this));
}
Try this. Done
will be runned after the promises will be resolved. You can return another promise form "do your mobile stuff" section to delay execution of third section like that:
this.mobilePromise = this.mobile.fetch()
.then(function(){
// do your mobile stuff
var moreMobileDetails = new MoreMobileDetails();
return moreMobileDetails.fetch();
}.bind(this))