title: Asynchronous node js "For" loop with database query
body: <p>Here is the "for" loop to run query(SQLite3 database) for each "id" in an array.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>qry = "SELECT patients.*, patient_visits.visit_id,patient_visits.patient_id, patient_visits.visitdate, patient_visits.visittime FROM patients LEFT JOIN patient_visits ON patients.id = patient_visits.patient_id "+where+" GROUP BY patients.id ORDER BY patients.id  DESC LIMIT "+limit+" OFFSET "+offset;
  db.all(qry, (err, results) =&gt; {
      if(err){
          response.error = err;
          res.send(response);
      }else{
          response.patients = patients;
          for (var i = 0; i &lt; patients.length; i++) {
              response.patients[i].check = "false";
              var patient = response.patients[i];
              db.each("SELECT visit_id FROM patient_visits where patient_id='"+patient.id+"' AND visitdate &gt;='"+moment().format('YYYY-MM-DD')+"'", function(err, row) {
                  if (row) {
                      response.patients[i].check = "true";
                  }
              });
          }
      }
      res.send(response);
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>The problem is that the for loop continues before the query is finished. Is there a way to check if the query has finished?</p>