代码之家  ›  专栏  ›  技术社区  ›  Datsik

如何执行多个异步函数(不嵌套)以提高性能,但要等待它们完成才能继续

  •  0
  • Datsik  · 技术社区  · 10 年前

    我一直在使用 Golang 有一段时间了,但我喜欢写Javascript,所以我又改回来了,但在 戈兰尼 你可以使用 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() 因为这样他们就可以按订单和性价比进行加工。我希望它们一起运行,然后等待所有异步回调完成,然后继续。

    1 回复  |  直到 10 年前
        1
  •  1
  •   MinusFour    10 年前

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