title: How can I execute a statement AFTER a loop finishes in javascript?
body: <p>I'm querying a mongo database to retrieve the tiles for the display in rougelike game. This is the function I use: </p>
  
  <pre><code>function get_display(){
      var collections = ['austinsroom'];
      var db  = mongojs(uri, collections);
      var temphtml = '';
  
      for(var j = 0; j &lt; 3; j++) {
          console.log("y=" + String(j));
          db.austinsroom.find({"y": j}, {}).sort({"x": 1}, function(err, records) {
              if(err) {
                  console.log("There was an error executing the database query.");
                  return;
              } 
              var i = records.length;
              while(i--) {
                  temphtml += records[i].display;
              }   
              temphtml += '&lt;br&gt;';
              //console.log(temphtml);
              //return temphtml;
              //THE ONLY WAY I CAN GET ANYTHING TO PRINT IN THE CONSOLE IS IF I PUT IT INSIDE THE LOOP HERE
              });
          //console.log(temphtml);
          //return temphtml;
          //THIS DOES NOTHING
      }
      //console.log(temphtml);
      //return temphtml;
      //THIS DOES NOTHING
  }
  get_display();
  </code></pre>
  
  <p>If I put the <code>console.log(temphtml)</code> inside the loop, it prints out three times which isn't what I want. I only want the final string (i.e. <code>...&lt;br&gt;...&lt;br&gt;...&lt;br&gt;</code>. Also I can't ultimately return the <code>temphtml</code> string, which is actually the important thing. Is this some quirk of javascript? Why would it not execute statements after the loop?</p>
  
  <p>Also: is there a better way to retrieve every element of a grid that's stored in a mongo database, in order, so it can be displayed properly? Here's what the mongo documents look like:</p>
  
  <pre><code>{
      "_id": {"$oid": "570a8ab0e4b050965a586957"},
      "x": 0,
      "y": 0,
      "display": "."
  }
  </code></pre>
  
  <p>Right now, the game is supposed to display a "<code>.</code>" in all empty spaces using the x and y values for the coordinates. The database is indexed by "x" values.</p>