Converting Mongoose model functions to be Promise and callback friendly simultaneously

I just started using promises in one of my Node.js applications after watching the callback hell in some of the code there.

I was going to use Q but while checking the different options I stumbled upon Bluebird and I liked it.

At some time I checked how Mongoose works with promises and discovered that many functions return a promise and also the queries’ exec() returns a promise too. The Promise in Mongoose is mpromise.

However I decided to stick to a single implementation of Promise for my entire application to have something as a standard and predictable way to use “promisified” functions. And this happened to be Bluebird. It’s huge(features) and I like it!

The first thing to “clean” was a function in one of my Mongoose’s models: User.create() – a custom static function that overrides the default create function. I needed the override to be able to receive custom structured arguments and also to do some changes before the model data is saved. I changed the way I handle the create later by removing it and using pre-hooks instead but this is a good example to show and is like a repeatable template for any other function that is going to be converted the same way.

Let’s see the original Promise-free function:

userSchema.static('create', function (data, cb) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
  });
  return user.save(cb);
});

You can see that User.create() receives a data object literal and executes the callback cb after it’s saved.

An example usage of create will be:

User.create({
  facebookId: '68yc7j9y4f64',
  name: 'Iliyan Trifonov',
  photo:'https://...'
}, function userCreateCb (err, user) {
  if (err) {
    return console.error(err);
  }
  if (!user) {
   return console.error('User not created!');
  }
  console.info('User created successfully!', user);
});

Now let’s make User.create return a promise:

First we promisify the model with:

Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);

and then the create function will look like:

userSchema.static('create', function (data) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
 });
 return user.saveAsync();
});

Now we should handle the resolve and reject:

User.create({
  facebookId: '68yc7j9y4f64',
  name: 'Iliyan Trifonov',
  photo:'https://...'
}).then(function (user) {
  console.info('User created successfully!', user);
}).catch(function (err) {
  console.error('Error creating the user!', err);
});

For now I am experimenting with the then(resolveCb)/catch(errorCb) combination but it can be changed to then(resolveCb, rejectCb) or then(resolveCb)/then(null, rejectCb).

But what about the rest of the code that depends on User.create to use a callback?

Let’s add the callback argument again:

userSchema.static('create', function (data, cb) {
  var user = new User({
    facebookId: data.facebookId,
    accessToken: hat(),
    name: data.name,
    photo: data.photo
  });
  return user.saveAsync().then(function (user) {
    return cb(null, user);
  }).catch(function (err) {
    return cb(err);
  });
});

And now the create function will work with the legacy code and the new Promises code simultaneously!

 

StrongLoop | Promises in Node.js with Q – An Alternative to Callbacks

Source: StrongLoop | Promises in Node.js with Q – An Alternative to Callbacks

One thing you should use when you feel you’re reaching the pyramid of doom.

I am currently using Promises heavily in one of the projects I currently work on: Notepads. I use bluebird as it is a very nice, complete and a clever Promises library that goes beyond the original specification (and saves you time).

Performance Showdown: Node.js vs. io.js v2.0.0

We benchmarked two versions of Node.js, and two versions of io.js. Here we’ll share with you what what we found out and detail the full results!

Source: Performance Showdown: Node.js vs. io.js v2.0.0

Also check the comments there for better charts.

Update: check these graphs too.

ES6 In Depth Articles ✩ Mozilla Hacks – the Web developer blog

Articles posted in ES6 In Depth

Source: ES6 In Depth Articles ✩ Mozilla Hacks – the Web developer blog

This is an on-going collection of articles that describes ES6 like they say it: in depth. I think it’s about time for us to start learning it. It’s a good reading coming from not just anybody but Mozilla.

You can follow the future articles by using blogtrottr.com with this rss feed.

147 JSJ io.js with Isaac Schlueter and Mikeal Rogers – Javascript Jabber – DevChat.tv

Talks about why io.js was started and how working more and faster with node/io and V8 is actually a great thing.

Source: 147 JSJ io.js with Isaac Schlueter and Mikeal Rogers – Javascript Jabber – DevChat.tv

124 JSJ The Origin of Javascript with Brendan Eich – Javascript Jabber – DevChat.tv

Source: 124 JSJ The Origin of Javascript with Brendan Eich – Javascript Jabber – DevChat.tv

Very interesting, funny and informative podcast with Brendan Eich. You can also read the transcript at the bottom of the page. I really like to read about the people behind a famous software. It shows how good is to be alive, to be a developer and to be a smart guy.

MountainWest JavaScript 2014 – Browser Package Management by Guy Bedford – YouTube

A very interesting presentation of jspm(a browser package management) by Guy Bedford. For me there are multiple parts in this video that got my attention from the very beginning of the presentation: as a beginning-to-be-better JavaScript developer I was interested to see and hear about require.js, its configuration and its future, SystemJS, ES6 modules, etc. Check it out!

https://youtu.be/MXzQP38mdnE

 

nativescript.org : Cross-Platform Native Development with Javascript

Build truly native iOS, Android and Windows Phone apps with Javascript and CSS. Try NativeScript open-source framework for cross-platform development.

Source: Cross-Platform Native Development with Javascript

After trying Ionic I was very happy with the current condition of the mobile apps frameworks that give you the possibility to write in JavaScript only. This one goes a step further by not using the WebView component to render a local web page but uses native UI components. Let’s see how it is. Check on their website for a very easy start!