【问题标题】:How to make sure that a foreach loop running async calls finished?如何确保运行异步调用的 foreach 循环完成?
【发布时间】:2017-09-21 19:02:00
【问题描述】:

我有一个 foreach 循环,我在其中调用一个异步函数。如何确保所有异步函数都调用了指定的回调函数,然后运行一些东西?

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

    保留一个柜台。 示例:

    const table = [1, 2, 3];
    const counter = 0;
    
    const done = () => {
         console.log('foreach is done');   
    }
    
    table.forEach((el) => {
       doSomeAsync((err, result) => {
          counter++;
          if (counter === 3) {
             done();
          }
       });
    });
    

    正如另一个答案所说,您可以使用非常好的 async 包。但为了它,我建议使用 Promises 并使用 Vanila Promise.all()。示例:

    const table = [1, 2, 3];
    
    Promise.all(table.map((el) => {
       return new Promise((resolve, reject) => {
           doSomeAsync((err, result) => {
                return err ? reject(err) : resolve(result); 
           });  
       });
    }))
    .then((result) => {
         // when all calls are resolved
    })
    .catch((error) => {
         // if one call encounters an error
    });
    

    【讨论】:

      【解决方案2】:

      您可以为此使用Async 库。它具有各种有用的实用功能。

      其中有一个 Queue 函数,可用于执行一组任务,当所有任务执行完毕时,您会收到一个回调,您可以在其中做任何您想做的事情。您还可以控制队列的并发性(一次并行执行多少个任务)。

      这是一个示例代码-

      // create a queue object with concurrency 2
      var q = async.queue(function(task, callback) {
          console.log('hello ' + task.name);
          callback();
      }, 2);
      
      // The callback function which is called after all tasks are processed
      q.drain = function() {
          console.log('all tasks have been processed');
      };
      
      // add some tasks to the queue
      q.push({name: 'foo'}, function(err) {
          console.log('finished processing foo');
      });
      q.push({name: 'bar'}, function (err) {
          console.log('finished processing bar');
      });
      

      【讨论】:

      • 是的,但遗憾的是,我不知道并发性。
      • 然后使用并发1。它会一个接一个地运行你的任务。
      猜你喜欢
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2019-03-25
      • 2020-08-02
      • 2021-11-13
      相关资源
      最近更新 更多