promise.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // import async to make control flow simplier
  2. var async = require('async');
  3. // import the rest of the normal stuff
  4. var mongoose = require('../../lib');
  5. require('./person.js')();
  6. var Person = mongoose.model('Person');
  7. // define some dummy data
  8. var data = [
  9. { name : 'bill', age : 25, birthday : new Date().setFullYear((new
  10. Date().getFullYear() - 25)) },
  11. { name : 'mary', age : 30, birthday : new Date().setFullYear((new
  12. Date().getFullYear() - 30)) },
  13. { name : 'bob', age : 21, birthday : new Date().setFullYear((new
  14. Date().getFullYear() - 21)) },
  15. { name : 'lilly', age : 26, birthday : new Date().setFullYear((new
  16. Date().getFullYear() - 26)) },
  17. { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
  18. Date().getFullYear() - 1000)) },
  19. ];
  20. mongoose.connect('mongodb://localhost/persons', function (err) {
  21. if (err) throw err;
  22. // create all of the dummy people
  23. async.each(data, function (item, cb) {
  24. Person.create(item, cb);
  25. }, function (err) {
  26. // create a promise (get one from the query builder)
  27. var prom = Person.find({age : { $lt : 1000 }}).exec();
  28. // add a callback on the promise. This will be called on both error and
  29. // complete
  30. prom.addBack(function () { console.log("completed"); });
  31. // add a callback that is only called on complete (success) events
  32. prom.addCallback(function () { console.log("Successful Completion!"); });
  33. // add a callback that is only called on err (rejected) events
  34. prom.addErrback(function () { console.log("Fail Boat"); });
  35. // you can chain things just like in the promise/A+ spec
  36. // note: each then() is returning a new promise, so the above methods
  37. // that we defined will all fire after the initial promise is fulfilled
  38. prom.then(function (people) {
  39. // just getting the stuff for the next query
  40. var ids = people.map(function (p) {
  41. return p._id;
  42. });
  43. // return the next promise
  44. return Person.find({ _id : { $nin : ids }}).exec();
  45. }).then(function (oldest) {
  46. console.log("Oldest person is: %s", oldest);
  47. }).then(cleanup);
  48. });
  49. });
  50. function cleanup() {
  51. Person.remove(function() {
  52. mongoose.disconnect();
  53. });
  54. }