当完成有限循环内的所有异步函数时

时间:2014-03-09 05:24:00

标签: javascript asynchronous

只有在有限循环中的所有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}}后执行?

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));
    });
});