title: How to wait for nested forEach statements with mongodb queries inside to return function
body: <p>I am having a hard time figuring out the asynchronous behaviour of nested <code>forEach()</code> functions with <code>node.js</code>. I am not sure where I should create and return a promise and so on.</p>
  
  <p>I have tried wrapping all the logic of the <code>getFeed()</code> function into a <code>return new Promise()</code>, but I think resolve is called before the nested <code>forEach()</code>'s are done.</p>
  
  <pre><code>friends = user_info.friends;
  
  function GetFeed() {
      let post_ids = [];
      try {
          friends.forEach(async function(friend_id) {
          const posts = await db.collection('users').findOne(
                { _id: ObjectId(friend_id) },
                { projection: { posts: 1 }}
          );
          posts.posts.forEach(function(post_id) {
                console.log(post_id);
                post_ids.push(post_id);
             });
          });
          return new Promise((resolve, reject) =&gt; {
              resolve(post_ids);
          });
      } catch (err) {
           return res.status(500).json({ error: 'Internal server error, unable to collection post ids from the database.' });
      }
  }
  
  GetFeed()
    .then((post_ids) =&gt; {
          console.log(post_ids);
          return res.status(200).json({ post_ids: post_ids });
     })
  </code></pre>
  
  <p>the console.log() statements reveal that the <code>GetFeed().then()</code> executes before the <code>console.log()</code> statement in the inner <code>forEach</code> loop. I expect that the <code>GetFeed().then()</code> console.log would wait for the nest <code>forEach</code> logic to finish and then console.log the result.</p>