Switching out callbacks with promises in Mongoose

http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/


Working with promises and mongoose just became a whole lot easier with the 4.1 release, which added the ability to specify alternative promise libraries. Prior to that, promise support was limited to the mpromise way of using promises. For some folks, including myself, this meant there wasn't a friendly .catch method available to the promise chain. In this post, I'll quickly cover how to switch over to other supported promise libraries and show how using promises can clean up your mongoose callbacks.

Normally, when using mongoose, you just need to require it. In order to switch out the promise provider, you'll also need to require the promise library and pointmongoose.Promise to it. In the following example, I set the promise library to bluebird:

var mongoose = require('mongoose');
// set Promise provider to bluebird
mongoose.Promise = require('bluebird');

Here's the example for using native promises or q:

// q
mongoose.Promise = require('q').Promise;
// native promises
mongoose.Promise = global.Promise;

That's as simple and non-hacky as one could hope for. Next up, I'll show what typical mongoose callbacks look like and how you can swap those out for promises. In these last examples, I'll look up a user by id, update the user's name, and save it:

// error first callback style
User.findById('123', function(err, user) {
  if (err) {
    return console.log('error:', err);
  }

  user.name = 'Robert Paulson';

  user.save(function(err) {
    // yet another err object to deal with
    if (err) {
      return console.log('error:', err);
    }
    console.log('updated user: ' + user.name);
    // do something with updated user
  });
});

The above callback example shows the first level of nesting and multiple error handlers. That's not too bad, but with more logic it can easily become visually overwhelming. In the last example, I'll show what the same task looks like using promises. We'll switch to using Model queries that return a promise via the .exec() function.

var promise = User.findById('123').exec();

promise.then(function(user) {
  user.name = 'Robert Paulson';

  return user.save(); // returns a promise
})
.then(function(user) {
  console.log('updated user: ' + user.name);
  // do something with updated user
})
.catch(function(err){
  // just need one of these
  console.log('error:', err);
});

Note that there was only one error handler for both of the promises, findById(id).exec()and user.save(). For me, the benefit of using promises is really in the ability to read what's going on in the code and to consolidate error handling into one place with the option to break that out if needed. If that interests you, give promises in mongoose a try.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值