【发布时间】:2016-06-11 13:44:00
【问题描述】:
我使用的技术是 Node.js、express 和 MongoDB。
我有一个名为“getAllRecipes”的方法,它可以在数据库中查询所有食谱——这很好用。
在“getAllRecipes”回调方法中,然后我循环每个条目/食谱以获取它的注释和 cmets。循环内的任务被放置在一个闭包内,以模仿“让”,否则每个recipeID都是相同的。
现在我添加对数组的进一步调用以与“async.series”结合使用。 首先,我调用“getRecipeNotes”,当它返回时,我在“getRecipeNotes”回调方法中调用“getRecipeComments”。
最终输出显示如下内容:
[
{
"_id": "56d070ac7c3965e85d3ebd38",
"userID": "56cf383a1f8303082484f35f",
"name": "Chocolate cake",
"instructions": "Add mixture to bowl, and then mix",
"dateTimeSubmitted": "2016-02-26T15:35:08.868Z",
"tags": "cooking, cake, chocolate",
"active": 1,
"notes": [],
"comments": []
},
{
"_id": "56d070ac7c3965e85d3ebd3a",
"name": "num1",
"quantity": "5",
"notes": [],
"comments": []
}, ...]
每一个 'notes' 和每一个 'cmets' 都是空数组。
我检查了 cmets 集合,并且有一个针对 recipeID 的条目:“56d070ac7c3965e85d3ebd38”。
如果我修改 'getRecipeComments' 方法以返回每个配方的所有 cmets,那么所有 cmets 都会返回。
另外,如果我使用 recipeID 保持查询并在 getAllRecipes 方法之外使用 recipeID 进行调用:“56d070ac7c3965e85d3ebd38”,那么它也可以正常返回数据......只是不使用 getAllRecipes 方法。
获取所有食谱:
function getAllRecipes( db, callback )
{
//query( db, {}, 'recipes', callback );
query( db, {}, 'recipes', function( err, recipeData )
{
tempArray = recipeData.slice();
if( err || !tempArray.length )
callback( err );
else
{
var taskArr = [];
for( var i=0; i < tempArray.length; i++ )
{
(function()
{
var tID = tempArray[ i ]._id;
taskArr.push( function( iCallback )
{
getRecipeNotes( db, tID, function( err2, noteData )
{
getRecipeComments( db, tID, function( err3, commentData )
{
if( err2 )
{
iCallback( err2 );
return;
}
if( err3 )
{
iCallback( err3 );
return;
}
for( var j=0; j < tempArray.length; j++ )
{
if( tempArray[ j ]._id === tID )
{
tempArray[ j ].notes = noteData;
tempArray[ j ].comments = commentData;
}
}
iCallback();
});
});
});
})();
}
async.series( taskArr, function( err )
{
callback( err, tempArray );
} );
}
});
}
getRecipeComments:
function getRecipeComments( db, recipeID, callback )
{
query( db, { recipeID : recipeID }, 'comments', callback );
}
查询:
function query( db, query, strColl, callback )
{
var coll = db.get( strColl );
coll.find( query, function( err, doc )
{
if( err )
console.log( err );
callback( err, doc );
});
}
我还将对“getRecipeNotes”和“getRecipeComments”的调用分成两个单独的任务,但结果是一样的。
你能明白为什么笔记或 cmets 拒绝返回吗?
【问题讨论】:
标签: node.js mongodb express asynchronous closures