title: How to send res.json() in Express JS from a for loop
body: <p>I am trying to send a json response when an API call is triggered from front-end, I'm not able to send the <code>res.json()</code> when I am getting the data from a for loop. Where I am writing a query to search in multiple Tables. I am using RethinkDB.</p>
  <p>I want <code>res.json()</code> to send data after the query, But I don't understand what mistake I am doing. :(</p>
  <p>Thanks in advence</p>
  <h1>zeasts</h1>
  <p>Here is the following code and <a href="https://jsfiddle.net/1bwxLjqs/1/" rel="nofollow noreferrer">Fiddle Link</a> too.</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>const express = require("express");
  const router = express.Router();
  const moment = require('moment');
  const r = require('rethinkdb');
  const tableNameDB = ['assets', 'alerts',  'destinations']
  
  
  router.post('/', (req, res, next) =&gt; {
          let resData = []
          let searchValue = req.body.searchValue,
              tableName = req.body.tableName;
          newCallForSearch(res, searchValue, resData)
      })
  
  function newCallForSearch (res, searchValue, resData){
      let anArray = ['captain']
      for(var i = 0; i&lt;tableNameDB.length; i++){
          let tabName = tableNameDB[i]
          r.table(tableNameDB[i]).filter(function(doc) {
              return doc.coerceTo('string').match(searchValue);
          }).run(rethink_conn, (err, cur) =&gt; {
             // console.log(cur)
              if (err) {
                  return 0
              } else {
                  cur.toArray((err, result) =&gt; {
                      if (err) {
                          return 0
                      } else if (result) {
                          let Results = []
                          Results = Object.values(result).slice(0,10)
                          var newResults = Results.map(function() {
                              resData = Object.assign({'tableName': tabName},{'data' : result});
                              anArray.push(resData)
                          })
                      }
                  })    
                  
              }
                  
          })
      }   
      res.status(200);
      res.json(anArray); 
  }
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>