gpt4 book ai didi

node.js - async.each 不处理 Mongoose 查找功能

转载 作者:搜寻专家 更新时间:2023-11-01 00:20:03 24 4
gpt4 key购买 nike

我有以下代码:

    async.each(arrayUser, function (user, callback) { //loop through array
console.log('1');
async.each(user.parentOf, function (child, callback1) { //loop through array
console.log(2);
models.Students.find({
'_id': child._id
},
function (err, foundStudent) {
console.log('3');
callback1();
},
function (err) {
console.log("InnerLoopFinished");
callback();
});
}, function (err) {
console.log("OuterLoopFinished");
console.log('Process Finished');
});
});

arrayUser 是这样创建的:

    var arrayUser = [];
users.forEach(function (user) {
var arrayUser1 = {
parent: {
_id: user._id,
firstName: user.firstName,
lastName: user.lastName
},
userRoleID: user.userRoleID.length,
parentOf: user.parentOf

};
arrayUser.push(arrayUser1);
});

user.parentOf 的示例是:

    user.parentOf = [{
studentLastName: 'Flores',
studentFirstName: 'Aedan',
studentID: 111444,
_id: 5a596979ea2d7a360c75948c
},
{
studentLastName: 'Moses',
studentFirstName: 'Chase',
studentID: 111756,
_id: 5a596979ea2d7a360c759489
}
]

我的问题是,即使使用 async.each 函数仍然无法正确运行。当它到达 models.Students.find 函数并运行下一个回调时,它似乎遇到了障碍。

在转到下一个用户之前,我需要完全运行 InnerLoop。我按照 nodejs Async.each Nested loop Confusion 的正确答案但没有结果。我已尝试将 models.Students.find 函数更改为 findOneAndUpdate,我得到了相同的结果。

我想我需要补充一点,我需要找到多个用户,每个用户都有一个内部数组。如果我只有一个用户(没有外循环),它工作正常。

我的 console.log 是:1, 2, 1, 2, 1, 2 ... 3, 3, 3...

我需要它是 1、2、3、1、2、3。

最佳答案

我们需要使用 async.eachSeries() 而不是 async.each()。这是符合您期望的工作代码段 1、2、3、1、2、3。

async.eachSeries(arrayUser, function (user, callback) { //loop through array
console.log('1');
async.eachSeries(user.parentOf, function (child, callback1) { //loop through array
console.log(2);
models.Students.find({
'_id': child._id
},
function (err, foundStudent) {
console.log('3');
callback1();
});
},function (err) {
console.log("InnerLoopFinished");
callback();
});
}, function (err) {
console.log("OuterLoopFinished");
console.log('Process Finished');
});
});

这是因为 eachSeries 函数按顺序在 iteratee 函数中执行(在上一次迭代完成后等待 callback() 被调用)所以输出为不负众望

关于node.js - async.each 不处理 Mongoose 查找功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48959289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com