Using JavaScript Promises with Backbone.sync

Published on by Morgan Ney

Using JavaScript Promises with Backbone.sync is doable with a few caveats. First, jQuery's $.ajax method (used by Backbone) returns a Deferred object which isn't Promises/A+ compliant. This is ok because the Deferred is "thenable" so we can cast it to a compliant promise object. Second, the onFulfilled handler of your promise's then() method is not passed the same arguments as the success() callback used by Backbone.sync. Namely, the fetched model or collection is not passed to then()'s onFulfilled handler, but rather the raw server response. However, the fetched model or collection has been synced and is ready for use.

Promises are really useful when syncing your models and/or collections in a sequence, for example dependent dropdowns. If your browser hasn't fully implemented promises, there is a polyfill available. Here is an example of how you might use promises with a Backbone project.

Relevant to  JavaScript, Backbone, Promise, jQuery
Get in Touch

BizzyBtyes is owned by Morgan Ney, a father, husband, and web developer originally from the San Francisco Bay Area and now living in Coarsegold, Ca. just south of Yosemite.