我一直在使用Golang
很长一段时间,但我喜欢编写Javascript,所以我已经切换回来了,但在Golang
中你可以使用sync.WaitGroup
执行多个{{ 1}}并等待他们完成,例如:
goroutines
那么我怎样才能在Javascript(Node)中完成这样的事情。 这就是我目前正在使用的内容:
var wg sync.WaitGroup
for _, val := range slice {
wg.Add(1)
go func(val whateverType) {
// do something
wg.Done()
}(val)
}
wg.Wait() // Will wait here until all `goroutines` are done
// (which are equivalent to async callbacks I guess in `golang`)
我不想将每个router.get('/', function(req, res, next) {
// Don't want to nest
models.NewsPost.findAll()
.then(function(newsPosts) {
console.log(newsPosts);
})
.error(function(err) {
console.error(err);
});
// Don't want to nest
models.ForumSectionPost.findAll({
include: [
{model: models.User, include: [
{model: models.Character, as: 'Characters'}
]}
]
})
.then(function(forumPosts) {
console.log(forumPosts);
})
.error(function(err) {
console.error(err);
});
// Wait here some how until all async callbacks are done
res.render('index', { title: 'Express' });
});
嵌套到承诺的回报中,因为它们将按顺序和成本绩效进行处理。我希望它们一起运行然后等待所有异步回调完成然后继续。
答案 0 :(得分:1)
您需要使用支持Promise.all
的库:
router.get('/', function(req, res, next) {
// Don't want to nest
var p1 = models.NewsPost.findAll()
.then(function(newsPosts) {
console.log(newsPosts);
})
.error(function(err) {
console.error(err);
});
// Don't want to nest
var p2 = models.ForumSectionPost.findAll({
include: [
{model: models.User, include: [
{model: models.Character, as: 'Characters'}
]}
]
})
.then(function(forumPosts) {
console.log(forumPosts);
})
.error(function(err) {
console.error(err);
});
Promise.all([p1, p2]).then(function(){
// Wait here some how until all async callbacks are done
res.render('index', { title: 'Express' });
});
});