我正在开发一个 node.js 项目,在该项目中我需要与 mongoDb 数据库进行通信。我目前正在编写一个函数来使用 node-mongodb-native 模块在我的数据库中查找一些数据。一切正常,但我的代码看起来像是回调中的回调中的回调中的回调中的回调...
我创建这个函数是为了防止我每次想要访问数据库时都使用回调。我现在只需要调用这个函数。
module.exports.find = function(query, projection, callback){
db.open(function(err, db){
if(err) throw err;
db.collection('rooms', function(err, collection){
if(err) throw err;
collection.find(query, projection, function(err, cursor){
if (err) throw err;
cursor.toArray(function(err, find){
db.close();
callback(err, find);
});
});
});
});
};
有没有办法减少这种代码接收?
最佳答案
如果您只是想知道如何合理地清理回调并确定数据库范围:
module.exports.find = function(query, projection, callback){
var local_db;
function db_open(err, db) {
if(err) throw err;
local_db = db;
local_db.collection('rooms', handle_homes_collection);
}
function handle_homes_collection(err, collection){
if(err) throw err;
collection.find(query, projection, handle_find_query);
}
function handle_find_query(err, cursor){
if (err) throw err;
cursor.toArray(function(err, find){
local_db.close();
callback(err, find);
});
}
db.open(db_open);
};
关于javascript - 处理回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17333001/