Switching out callbacks with promises in Mongoose
来源:互联网 发布:淘宝挣钱吗 编辑:程序博客网 时间:2024/05/01 04:57
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 bluebirdmongoose.Promise = require('bluebird');
Here's the example for using native promises or q
:
// qmongoose.Promise = require('q').Promise;// native promisesmongoose.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 styleUser.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.
- Switching out callbacks with promises in Mongoose
- Virtual Switching in Solaris with Crossbow VNICs
- Callbacks with Delegates [转]
- Timer class with queued callbacks
- State Machines with C Callbacks
- Promises
- Refactoring Mongoose with Q
- Script Callbacks in ASP.NET
- Node.js : Using Promises with mongoosejs
- [翻译] We have a problem with promises
- Out With the Old and in With the New
- Callbacks
- callbacks
- Switching between Views with a UISegmentedControl 转
- Switching Views with a UISegmentedControl - Revisited 转
- Dynamic Switching the Wallpages in Ubuntu 10.04
- Resolution Switching in DirectShow Camera Application
- Fast switching between ViewModels in Caliburn.Micro
- Gradle
- 最简单的jsp+servlet的增删改查代码
- okhttp完全解析版
- [WIN32]Windows API宏SendMessage
- oracle各个版本的exp/imp兼容性
- Switching out callbacks with promises in Mongoose
- 中午午休
- cookie.js
- Node.js : Using Promises with mongoosejs
- nwu 新生题解【第一套】
- div加链接 html给div加超链接实现点击div跳转的方法[申明:来源于网络]
- QT中setOverrideCursor 和restoreOverrideCursor函数
- Linux下通过scsi-target-utils搭建多硬盘共享存储
- Mysql 从零开始