keralajs-promises



keralajs-promises

1 0


keralajs-promises

Slides of My talk on "Promises in JavaScript"

On Github revathskumar / keralajs-promises

Promises in JavaScript

ABOUT ME

What are promises?

  • A pattern to work with asyncronous operations much neatly.
  • A function return a object called promise, which is the eventual result of the operation.
  • operated via then method.
  • States : Pending / Fulfilled / Rejected
promise.then(onFulfilled, onRejected)

Why we need promises?

  • Chaining
  • Attach multiple callbacks
  • Pool operations
  • Easy error handling
User.get(1,{
  success: function(){
    console.log('Success');
  },
  error: function(){
    console.log('Error');
  }
})

In promise

User.get(1).then(
  function(){
    console.log('Success');
  }, 
  function(){
    console.log('Error');
  }
);
User.get('1', {
  success: function(){
    Accounts.get('1', {
      success: function(){
        Accounts.update({twitter: @addyosmani}, {
          success: fucntion(){
            console.log('Success')
          },
          error: function(){
            console.log('Error');
          }
        })
      },
      error: fucntion(){
        console.log('Error');
      }
    })
  },
  error: function(){
    console.log('error');
  }
});
User.get(1)
  .then(Accounts.get)
  .then(function(){
    return Accounts.update({twitter: @addyosmani})
  })
  .then(function(){
    console.log('Success');
  })
  .then(undefined, function(){
    console.log('Error');
  });
var User = (function(){
  function get(user_id){
    var promise = new Aplus();
    $.get('/users/' + user_id, {
      success: function(data){
        promise.fulfill(data.account_id);
      },
      error: function(){
        promise.reject('Error');
      }
    });
    return promise;
  }

  return {
    get: get
  }
})

Pooling

Aplus.pool(
 asyncFunc(),
 anotherAsyncFunc()
)
.then(asyncSuccess, asyncError);

Using jQuery

$.when(
  $.ajax( "/page1.php" ),
  $.ajax( "/page2.php" ),
)
.then(onSuccess, onError);

jQuery : multiple callbacks

$.when(function(){
    console.log('Hello Promise');
})

.then(function(){
    console.log('Success1');
}, function(){
    console.log('Error1');
})

.then(function(){
    console.log('Success2');
}, function(){
    console.log('Error2');
});

Reference

http://promises-aplus.github.io/promises-spec/ http://wiki.commonjs.org/wiki/Promises/A https://github.com/rhysbrettbowen/Aplus/ http://api.jquery.com/category/deferred-object/