3

I'm working with Mongoose, and I'd like to use a promise approach with the Q library.

Not sure when to use the various methods nfcall,nfinvoke or wrap the APIs with denodeify/nfbind

Examples:

var p = Q.when(User.findOne({login: 'johndoe'}).exec());
p.then(...)

Or Something like:

Q.ninvoke(User, 'findOne', '{login:"johndoe"}').then(...)

Or wrapping the API like:

'use strict';

    //pUser.js Q/promise wrapper
    var Q = require('q'),
    mongoose = require('mongoose'),
    User = mongoose.model('User');

    exports.findOne = function() {
    return Q.denodefiy(User.findOne);
    }

    //and then use like:
    var pUser = require('pUser');

    pUser.findOne({...}).then(function(user) { ... });

I've also seen approaches like this which wrap every method with an nfbind or something similar

Thanks

Community
  • 1
  • 1
binarygiant
  • 6,362
  • 10
  • 50
  • 73
  • 1
    What's wrong with what you have? What exactly are you asking for? A request to list things is considered off-topic on SO. – Bergi Mar 12 '14 at 12:46
  • Being new to using Q, I want to know if heading down a particular path has consequences which may not exist with the "more correct" approach. I'll assume your response indicates I'm heading in the right direction. Not sure what the down vote was for however. In any case thanks. – binarygiant Mar 12 '14 at 14:14
  • 1
    Both approaches work. The only thing you might need to worry about is handling `this` correctly. If you would ask a more specific question like "*When to use promisify/nfbind vs nfcall/ninvoke/…?*" you probable would've gotten upvotes. You still might [edit] it :-) – Bergi Mar 12 '14 at 14:24

1 Answers1

3

Mongoose (at least in the last year or so) already returns promises that are Promises/A+ spec complaint.

You don't need to wrap them in Q promises unless you have to. Q, being promises/A+ complaint itself will gladly consume these promises and interop with them for you.

You can, for example use Q.all on three calls of find(...).exec().

 Q.all([
     User.find({route: foo}).exec(), // Q will detect that the values are 'thenable'
     User.find({route: bar}).exec(), // and will automatically assimilate them into a 
     User.find({route: baz}).exec()  // Q promise on its own. No explicit action needed.
]).spread(function(res1,res2,res3){
     // access results.
});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Ah, I remember reading it was A+ compliant, just didn't realize you have to call exec to make the call "thenable". Thank you – binarygiant Apr 16 '14 at 23:19