jquery - Two BackboneJS fetches and data gets swapped -


this our code inside single function. i'm beginning better 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 previous developer trying implement similar $q.all this.allpromise = [desktoppromise, mobilepromise];  $.when(this.desktoppromise).done(_.bind(function() {    // desktop stuff }, this)); $.when(this.mobilepromise).done(_.bind(function() {    // mobile stuff }, this));  if (this.allpromise) {   $.when.apply($, this.allpromise).done(_.bind(function() {     // stuff here if desktop     ....     // stuff here if mobile     ....   }, this)); } 

i noticed there times our data in our variable gets mixed between desktop , mobile. response api server fine. suspected api team returning wrong data until debugged our app, our code doing weird.

how can refactored data doesn't mixed up? told me in irc, "promises have weird behaviors".

let's rewrite little

this.desktop = new desktopitemmodel({device: 'desktop'}); this.desktoppromise = this.desktop.fetch()     .then(function(){         // desktop stuff     }.bind(this));   this.mobile = new mobileitemmodel({device: 'mobile'}); this.mobilepromise = this.mobile.fetch()     .then(function(){         // mobile stuff     }.bind(this))  $.when(this.desktoppromise, this.mobilepromise)     .done(function() {         // stuff here if desktop         // stuff here if mobile     }.bind(this)); } 

try this. done runned after promises resolved. can return promise form "do mobile stuff" section delay execution of third section that:

this.mobilepromise = this.mobile.fetch()     .then(function(){         // mobile stuff         var moremobiledetails = new moremobiledetails();         return moremobiledetails.fetch();     }.bind(this)) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -