title: Limiting amount of async BigQuery Jobs running on express server
body: <p>I have an express server that is pulling data from Google BigQuery. An <code>array</code> of objects is provided. I want to pull sales data for each <code>store</code> in a <code>district</code>, but the table holds sales information based only on <code>store</code> and doesn't have <code>district</code> information. I was accomplishing this by sending one query per <code>district</code>, but once the array has more than 50 district I get errors. The results are stored in individual CSV files by district. So it is convenient to send individual queries and dump it into the CSVs. BigQuery only allows 50 jobs at a given time. I am looking for the best way to adapt the below code to call <code>asyncQuery(query)</code> 50 times then only make the next call when a previous call has returned. I have been trying to work the job status using the <code>job.getMetadata()</code> but no luck yet.</p>
  
  <p>Thanks for any help you can offer</p>
  
  <pre><code>const array = [{
          district: "north"
          store: "1001,1002"
      },
      {
          district: "south"
          store: "1003"
      },{
          district: "west"
          store: "1004"
      }
  ]
  
  function apiCall(array) {
      array.forEach(element =&gt; {
          let stores = element.store.toString()
          let query = `SELECT store, sku, tot_sales, price
                        FROM big-query-table 
                        WHERE
                        store IN (${stores})`
          asyncQuery(query)
              .then(resp =&gt; {
                  console.log(resp)
              }).catch(err =&gt; {
                  console.error('ERROR:', err);
              })
      })
      return "Running Jobs"
  }
  
  function asyncQuery(sqlQuery) {
  
      const options = {
          query: sqlQuery,
          useLegacySql: false,
      };
  
      let job;
  
      return bigquery
          .createQueryJob(options)
          .then(results =&gt; {
              job = results[0];
              console.log(`Job ${job.id} started.`);
              return job.promise();
          })
          .then(() =&gt; {
              // Get the job's status
              return job.getMetadata();
          })
          .then(metadata =&gt; {
              // Check the job's status for errors
              const errors = metadata[0].status.errors;
              if (errors &amp;&amp; errors.length &gt; 0) {
                  throw errors;
              }
          })
          .then(() =&gt; {
              console.log(`Job ${job.id} completed.`);
              return job.getQueryResults();
          })
          .then(results =&gt; {
              const rows = results[0];
              return rows;
          })
          .catch(err =&gt; {
              console.error('ERROR:', err);
          });
  }
  </code></pre>