Barry M. Wong

UI Engineer + Designer

Blog

Promises in Javascript

August 27, 2013 at 6:11 pm | code

Never make a promise that you cannot commit. Fortunately, Javascript is trustworthy!

Basically, a promise is an async callback inside another async callback and that’s it. (You could keep doing callback inside another callback inside another and so on, but this is really ugly.) The promise is that code will be returned to you at some time. At that time, you can decide what you want to do with it.

Here is an expert from my team project PreLinked. This is using Backbone’s ajax and jQuery’s promises:

...
  fetchUser: function(){

 // assign promise to here
 var deferred = $.Deferred();
 var that = this;
 this.model.fetch()
 .done(function(data){
 // console.log('user attributes: ', that.attributes);
 // console.log('fetchUser success with data: ', data);
 // when the promise is delivered at some time resolve it here
 deferred.resolve(data);
 })
 .fail(function(error){ // if all fails
 console.log('fetchUser failed');
 // reject the promise
 deferred.reject('fetchUser failed');
 });
 // return the promise whenever it is ready
 return deferred.promise();
 },
...

Node.js also has a library for dealing with promises called Q.