如何“宣传”我自己的功能(位于另一个目录中)?这是我的代码:
// 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});
)
);
这是另一个文件
// 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);});
}
);
});
这是错误
/Users/Josh/Development/xWing/app.js:12
mongo.connectAsync()
^
TypeError: Object #<Object> has no method 'connectAsync'
答案 0 :(得分:3)
Promise带回了同步代码的品质。
鉴于您的API已经被承诺 - 您只需从您的函数返回一个承诺,然后使用它。
module.exports.connect = Promise.method(function(){
// do a bunch of stuff
return mongo.connectAsync().then(...
});
注意Promise.method
位并不是必需的,它只是将抛出的错误变成拒绝,以便让您保持安全,并确保您返回一个承诺,这是它的最佳做法并保护您免受意外事故的影响