Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Asynchronous JS with Promise (+ Workshop)

Asynchronous JS with Promise (+ Workshop)

Makara Wang

March 30, 2013
Tweet

More Decks by Makara Wang

Other Decks in Programming

Transcript

  1. function fetch(model) { var def = deferred(); model.fetch({ success: function(model)

    { def.resolve(model); }, error: function() { def.resolve(new Error('lorem')); } }); return def.promise; }
  2. deferred(new Model({id: 1})) .then(fetch) .then(function(model) { // ... }) //

    Or .end() .then(function() { // ... }, function(err) { // ... });
  3. var promiseA = deferred(valueA); var promiseB = promiseA.then(function(valueA) { return

    valueB; }); var promiseC = promiseB.then(function(valueB) { var def = deferred(); def.resolve(valueC); return def.promise; }); promiseC.then(function(valueC) {});
  4. async.waterfall([ function(callback) { // Load a user model. callback(null, user);

    }, function(user, callback) { // Call the login API. user.login({ success: function() { user.authenticated = true; callback(null, user); }, error: function() { callback(new Error('lorem')); } }); } ], function(err, user) {});
  5. // Or simply name it `login` function getLoggedInUser(user) { var

    def = deferred(); // A method that calls the login API. user.login({ success: function(data) { var loginUser = new User(data); def.resolve(loginUser); }, error: function() { def.resolve(new Error('lorem')); } }); return def.promise; }
  6. Work with Express.js app.get('/', function(req, res, next) { // This

    returns a promise. loadSomething(x).end(function(data) { res.send(y); // Or req.y = data; next(); }, next); });