只有在有限循环中的所有asyn函数都执行完毕后才需要执行next()
的方法。
Schema.pre('construct', function(next) { // << next()
var users = [123,234,345,456,...]
users.forEach(function(user) {
db.async_FindbyID(user, function(err, user){
this.users.push(user);
// can't put next() here or it'll be executed after the fist iteration alone
}.bind(something));
});
// can't put next() here because it'll be executed regardless of db.async_FindbyID
});
如何在内部next()
进行db.async_FindbyID
来电,并且只有在user
完成每个{{1}}后执行?
答案 0 :(得分:2)
保持处理的用户数量,当您处理完最后一个用户时,请运行下一个。
Schema.pre('construct', function(next) { // << next()
var users = [123,234,345,456,...]
var processed = 0;
users.forEach(function(user) {
db.async_FindbyID(user, function(user){
this.users.push(user);
if (++processed == users.length) {
next();
}
}.bind(something));
});
});