Asynchronous JS with Promise

Makara Wang
February 23, 2013

Asynchronous JS with Promise

Makara Wang

February 23, 2013

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

13 slides
  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. 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) {});
  4. // Or simply name it `login` function getLoggedInUser(user) { var

    def = deferred(); // Call the login API. user.login({ success: function() { user.authenticated = true; def.resolve(user); }, error: function() { def.resolve(new Error('lorem')); } }); return def.promise; }
  5. 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); });

More Decks by Makara Wang

Other Decks in Programming