title: Timing of query with mongoose and node
body: <p>I am completely desperate with this problem. I have a query Array which I stored so long in memory. With it, I call an API, fire my requests and store the result to MongoDB...no problem. Unfortunately I have no control reg. the API-Server and some Econnet/TCP/IP connection error make my app crash from time to time. </p>
  
  <p>To be able to resume my querying task, I wrote all my queries in my MonogDB and I want to track/record the queryState of each query being executed or not.</p>
  
  <p>My problem occurs when I try to get the queries back from Mongo into my method which fires the requests. Due to some timing/async problems (I guess), my queryArray stays undefined all the time and I don't get it solved...</p>
  
  <p>server.js:</p>
  
  <pre><code>//TEST
  var querymongo = require('./config/queryMongo');
  var queryobject = new querymongo;
  var queryArray = queryobject.results();
  </code></pre>
  
  <p><strong>queryArray stays undefined all the time...</strong></p>
  
  <p>queryMongo.js:</p>
  
  <pre><code>    //require mongo model + db connection
      var queryDB = require('./queryDB');
  
      //constructor
      ...
  
      //mongoRequest method
          this.mongoRequest = function(){
              console.log("Function mongoRequest called now!");
              return new Promise(function(resolve, reject){
                  queryDB.queries.find({'SearchIndex': 'All'}, function(err, doc){
                      if(err) return reject (err)
                      else resolve (doc)
                  });
              });
          }
  
      //resolve results
      this.results = function(){
          var queryArray = [];
          this.mongoRequest().then(function(doc, err){
               console.log(doc)
              queryArray = doc;
              return queryArray;
          }).catch(function(err){
              console.log(err)
              });
          }
  
  
  
  }
  module.exports = QueryMongo;
  </code></pre>
  
  <p>The console.log(doc) in the result method works, but returns all docs at the end of all code being executed. What is the problem here?</p>
  
  <p>I would be very thankful as this makes me crazy!</p>
  
  <p>Thanks</p>
  
  <p>Hucho</p>