Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 异步mongodb查找内部循环在返回所有数据之前提前完成_Javascript_Node.js_Mongodb_Asynchronous - Fatal编程技术网

Javascript 异步mongodb查找内部循环在返回所有数据之前提前完成

Javascript 异步mongodb查找内部循环在返回所有数据之前提前完成,javascript,node.js,mongodb,asynchronous,Javascript,Node.js,Mongodb,Asynchronous,我正在使用实用程序模块从Mongodb数据库返回项目。我想异步地做。我在试图归还这些物品时遇到问题 我想在所有User.find都完成后启动回调,此时async.each会提前终止,并且只从数据库中给我一个项,而它应该返回所有项 代码如下: async.each(lessons, function(lesson, next) { // For each item in lesson array if (_.isEmpty(lesson.lesson_grades) == true) {

我正在使用实用程序模块从Mongodb数据库返回项目。我想异步地做。我在试图归还这些物品时遇到问题

我想在所有User.find都完成后启动回调,此时async.each会提前终止,并且只从数据库中给我一个项,而它应该返回所有项

代码如下:

async.each(lessons, function(lesson, next) { // For each item in lesson array
    if (_.isEmpty(lesson.lesson_grades) == true) { // Check if the grades array is empty
        return;
    } else {
        async.each(lesson.lesson_grades, function(grade, next) { // For each grade in grade array
            User.find({ // Find user from grade user_id
                _id: grade.user_id,
            }, '-salt -hashedPassword', function(err, user) {

                grade["name"] = user[0].name; // Add name
                grade["email"] = user[0].email; // Add email

                next(); // !! I think this is where the problem lies, it fires next() once the first item has been returned - so it doesn't get to the other items !!
            });
        }, function(err) {
            next(lessons);
        });
    }
}, function(lessons, err) {
    return res.json(200, lessons); // Return modified lessons (with name and email) to browser, currently only returns one but returns them all if a setTimeout() is added, making it a premature callback problem
});

有人能给我指出正确的方向吗?我应该跟踪迭代吗?任何帮助都将不胜感激。

异步遵循的惯例是回调函数按顺序接受两个参数:错误和结果。错误和结果之间的区别很重要,因为异步在收到错误时会立即完成。说functionerr{nextlessons;}的部分是错误的-异步错误地将课程解释为错误,因为它是真实的。应改为:

function(err, result) {
    next(err, result);
}
或者实际上你可以用next替换函数

另外,在functionlessons的末尾,error应该是functionerror

另一件需要注意的事情是:您必须确保每个回调调用一次,并且只调用一次。但是如果它运行if块而不是else块,则永远不会调用next;异步永远不会结束。它不会阻止其他代码运行,但它永远不会返回res.json200,lessons;。它也可能会泄漏内存,我不确定


最后一件事:在回调中返回结果不会起任何作用。看起来您正试图从同步函数调用所有这些异步代码;这不管用。将调用res.json,但如果它返回一个值,那么您可能希望将该值用作其他地方的另一个回调函数的参数。但是我需要更多关于您尝试做什么的信息。

感谢您抽出时间回答。我已经做了你建议的改变,但我仍然有同样的问题。你能指导我如何重写它吗?自从你发布这个答案后,我已经试了一整天了。谢谢。您是如何从中获得输出的?另外,请注意我对答案的更改-最后的函数不应该作为参数,而应该是一个闭包变量。