luin / express-promise

❤️ Middleware for easy rendering of async Query results.
MIT License
316 stars 19 forks source link

What if step 2 need the result of step 1? #1

Closed rjyo closed 11 years ago

rjyo commented 11 years ago

Say sth like the following

async.waterfall([
  function(callback) {
    User.find(req.body.friendId).complete(callback);
  },
  function(friend, callback) {
    me.addFriend(friend).complete(callback);
  }
], done);
luin commented 11 years ago

I think this can be solved with the help of Promise:

var result = {};
result.user = User.find(req.body.friendId);
result.addFriend = result.user.then(function(friend) {
  return me.addFriend(friend);
});

res.json(result);

The query User.find() should be executed only once according to the spec of Promises/A+: http://promises-aplus.github.io/promises-spec/

rjyo commented 11 years ago

Cool!

If all I need is to do run the promises and just send back a 200 response if no error happened. (e.g. add a friend)

What should I do?

luin commented 11 years ago

res.json(User.find(req.body.friendId)); works well if you don't care about the response body, otherwise:

User.find(req.body.friendId).then(function() {
    res.json(/* response body */);
});
rjyo commented 11 years ago

Got it. Great lib!