title: ExpressJs wait till MongoDB fetch data and loop through before the output
body: <p>I'm having trouble in figuring this to work, I have one table from MongoDB (collection) for comments and another collection for Users. </p>
  
  <p>When the page load it looks up the comment collection and selects the relevant comments, and then it searches the user table to find the name of the user who made the comment, the data will be combined and then the response is sent. </p>
  
  <p>However, the output is sent before the data is fetched from the user table and added. How can I fix this, here is my code</p>
  
  <pre><code>  var output = []
    const Comments = require('comments.js')
    const Users = require('users.js')
  
    function delay( ) {
      return new Promise(resolve =&gt; setTimeout(resolve, 300))
    }
  
    async function delayedProcess(item) {
      await delay()
      Users.findById(item.user, async function(err, result) {
        Object.assign(item, {name: result.name})
        output.push(item)
      })
    }
  
    async function processArray(array) {
      const promises = array.map(delayedProcess)
      await Promise.all(promises)
      return res.json({data: output})
    }
  
  
    Comments.find({page_id: id}).sort({post_date:-1}).limit(6).then(function(data) {
      processArray(data)
    })
  </code></pre>