Reputation: 555
How do I "promisify" my own function (that lives in another directory)? Here's my code:
// app.js
// include database
var mongo = require('./mongo');
var promise = require('bluebird');
var u = require('./util.js');
var mongo.connect = promise.promisify(require(mongo.connect));
// connect to database
var ago = new Date(new Date()-60000); // 10m ago
var scope = {size:0.01};
mongo.connect()
.then(
mongo.endor.mapReduceAsync(u.mapTile, u.reduceTile,{
out: {replace:'deathstar'}, scope:scope,
query: {time:{$gte:ago}}, finalize:u.finalTile}))
.then(deathstar.find({},{fields:{_id:0, value: 1}})
.toArray(function(err, docs){
endor.insertAsync(_.map(docs, function(doc){return doc.value;}),{w:1});
)
);
And here's the other file
// mongo.js
var promise = require('bluebird');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
promise.promisifyAll(mongodb);
module.exports.connect = promise.method(function(){
// database environment
var database;
if (process.env.NODE_ENV == 'production'){database = pro;}
else{database = database = dev;}
module.exports.database = database;
// connect to database
return MongoClient.connectAsync(database)
.then(function(db){
module.exports.db = db;
promise.all([
db.createCollectionAsync('hoth', {w:1})
.then(function(collection){
collection.ensureIndexAsync()
.then(function(index){
module.exports.hoth = collection;
console.log(index+' hoth');
});
}),
db.createCollectionAsync('endor', {w:1})
.then(function(collection){
collection.ensureIndexAsync({})
.then(function(index){
module.exports.endor = collection;
console.log(index+' endor');
});
}),
db.createCollectionAsync('alderaan', {w:1})
.then(function(collection){
collection.ensureIndexAsync({time:-1, location:'2dsphere'})
.then(function(index){
module.exports.endor = collection;
console.log(index+' alderaan');
});
})
]).then(function(){callback(null);});
}
);
});
and here's the error
/Users/Josh/Development/xWing/app.js:12
mongo.connectAsync()
^
TypeError: Object #<Object> has no method 'connectAsync'
Upvotes: 4
Views: 2501
Reputation: 276496
Promises bring back the qualities of synchronous code.
Given your API is already promisified - You simply return a promise from your function and then use that.
module.exports.connect = Promise.method(function(){
// do a bunch of stuff
return mongo.connectAsync().then(...
});
Note the Promise.method
bit isn't required, it just turns thrown errors into rejections to give you throw safety and makes sure you return a promise so it's best practice and guards you against mishaps.
Upvotes: 3