gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:03:29 25 4
gpt4 key购买 nike

我需要一种方法来仅在有限循环内的所有异步函数执行完毕后才执行 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
});

如何在 db.async_FindbyID 对每个 user 执行完毕后从内部调用 next()

最佳答案

记录已处理的用户数,当您处理完最后一个用户后,运行下一步。

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

关于javascript - 当有限循环内的所有异步函数都完成时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278754/

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