如何为性能执行多个异步函数(非嵌套),但等待它们完成再继续

How can I do multiple async functions (not nested) for performance, but wait for them to finish before proceeding

本文关键字:等待 再继续 嵌套 执行 性能 函数 异步      更新时间:2023-09-26

我已经使用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`)

那么我如何在Javascript(Node)中完成这样的事情。这是我目前正在使用的:

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

我不想将每个.findAll()都嵌套在承诺的回报中,因为这样它们将按顺序和成本性能进行处理。我希望它们一起运行,然后等到所有异步回调完成,然后继续。

您需要使用支持 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' });
  });
});