[英]How can I do multiple async functions (not nested) for performance, but wait for them to finish before proceeding
I've been using Golang
for quite some time, but I love writing Javascript so I've switched back, but in Golang
you could use sync.WaitGroup
to perform multiple goroutines
and wait for them to finish, eg: 我已经使用
Golang
相当一段时间了,但是我喜欢编写Javascript,所以我切换回去,但是在Golang
您可以使用sync.WaitGroup
来执行多个goroutines
并等待它们完成,例如:
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`)
So how can I accomplish something like this in Javascript (Node). 因此,如何在Javascript(节点)中完成类似的操作。 This is what I'm currently working with:
这是我目前正在使用的:
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' });
});
I don't want to nest each .findAll()
into a return for the promise because then they will process in order and cost performance. 我不想将每个
.findAll()
嵌套到诺言的回报中,因为这样它们将按顺序和成本效益进行处理。 I'd like them to run together and then wait until all async callbacks are done and then proceed. 我希望它们一起运行,然后等到所有异步回调完成后再继续。
You'll need to use a library that supports Promise.all
: 您需要使用支持
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' });
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.