我有以下代码:
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');
});
});
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
以及user.parentOf的示例是:
user.parentOf = [{
studentLastName: 'Flores',
studentFirstName: 'Aedan',
studentID: 111444,
_id: 5a596979ea2d7a360c75948c
},
{
studentLastName: 'Moses',
studentFirstName: 'Chase',
studentID: 111756,
_id: 5a596979ea2d7a360c759489
}
]
Run Code Online (Sandbox Code Playgroud)
我的问题是,即使async.each该功能仍未正确运行.当它到达models.Students.find函数并且它运行下一个回调时似乎正在碰壁.
我需要完全运行InnerLoop才能继续下一步user.我在nodejs Async.each嵌套循环混乱中遵循了正确的答案,
但没有结果.我已经尝试将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');
});
});
Run Code Online (Sandbox Code Playgroud)
这是因为eachSeries函数按顺序在iteratee函数中执行(在完成上一次迭代并等待直到callback()被调用之后),因此它根据您的期望提供输出
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |