Javascript 展开嵌套回调
我在学习Node.js中使用回调风格的编程时遇到了令人沮丧的问题。我有一个对MongoDB数据库的查询。如果我传入一个函数在结果上执行,它会工作,但我宁愿将它展平并让它返回值。任何关于如何正确操作的帮助或指导都将不胜感激。这是我的密码:Javascript 展开嵌套回调,javascript,node.js,mongodb,callback,Javascript,Node.js,Mongodb,Callback,我在学习Node.js中使用回调风格的编程时遇到了令人沮丧的问题。我有一个对MongoDB数据库的查询。如果我传入一个函数在结果上执行,它会工作,但我宁愿将它展平并让它返回值。任何关于如何正确操作的帮助或指导都将不胜感激。这是我的密码: var getLots = function(response){ db.open(function(err, db){ db.collection('lots', function(err, collection){
var getLots = function(response){
db.open(function(err, db){
db.collection('lots', function(err, collection){
collection.find(function(err, cursor){
cursor.toArray(function(err, items){
response(items);
})
})
})
})
}
我想要更像这样的东西:
lots = function(){
console.log("Getting lots")
return db.open(openCollection(err, db));
}
openCollection = function(err, db){
console.log("Connected to lots");
return (db.collection('lots',findLots(err, collection))
);
}
findLots = function(err, collection){
console.log("querying 2");
return collection.find(getLots(err, cursor));
}
getLots = function(err, cursor) {
console.log("Getting lots");
return cursor.toArray();
}
最终的数据集将通过函数调用进行备份
问题是,我从Node.js得到一个错误,说err没有定义或者集合没有定义。由于某种原因,当我嵌套回调时,正确的对象被传递下来。当我尝试使用这种扁平样式时,它会抱怨事物没有定义。我不知道如何让它传递必要的对象。您需要的是通过npm为node提供的众多功能之一,并在node.js wiki上进行分类。我的具体建议是,您可以使用
async.falter
函数来完成这种类型的流,其中每个异步操作都必须按顺序执行,并且每个操作都需要上一个操作的结果
伪代码示例:
function getLots(db, callback) {
db.collection("lots", callback);
}
function findLots(collection, callback) {
collection.find(callback);
}
function toArray(cursor, callback) {
cursor.toArray(callback);
}
async.waterfall([db.open, getLots, find, toArray], function (err, items) {
//items is the array of results
//Do whatever you need here
response(items);
});
async是一个很好的流控制库。提供了一些特定的优势,如更好的调试和更好的同步函数执行安排。(尽管它目前不像async那样位于npm中) 下面是它在框架中的外观:
Frame(function(next){
db.open(next);
});
Frame(function(next, err, db){
db.collection('lots', next);
});
Frame(function(next, err, collection){
collection.find(next);
});
Frame(function(next, err, cursor){
cursor.toArray(next);
});
Frame(function(next, err, items){
response(items);
next();
});
Frame.init();
您给出的示例解决方案有什么具体错误?看起来是个好主意,也是一个很好的实现。问题是什么?您也可以尝试以下方法:针对此类问题创建。或者,问题是,我从Node.js收到一个错误,表示未定义err或未定义集合。由于某种原因,当我嵌套回调时,正确的对象被传递下来。当我尝试使用这种扁平样式时,它会抱怨事物没有定义。我不知道如何让它通过必要的物体。我在这个问题上加了这个评论。抱歉,不明确。实际上,
async.series
不会将参数传递给下一个调用。他需要async.falter
。当我使用它时,生成的数据集是否会传回链并返回到调用函数?我希望从这一系列回调中返回cursor.toArray()函数的结果。请查看异步文档。使用瀑布,每个函数的回调值作为参数传递给链中的下一个函数,最后一个函数的回调值作为“done”回调函数的参数。您可以根据需要链接结果。我将更新我的答案以包含一个示例。