title: Sending response after forEach nodeJS
body: <p>I'm developing an API in NodeJS that will send a response only after the foreach loop has been finished with the result of each operation done inside the loop.
  The problem now is that the code not wait until the foreach has finished to send the respond.</p>
  <p><strong>Request:</strong></p>
  <pre><code>  &quot;enterpriseName&quot;: &quot;myEnterprise&quot;,
    &quot;channels&quot;: [
      {
        &quot;provider&quot;: &quot;mail&quot;,
        &quot;contact&quot;: &quot;11111111111&quot;,
        &quot;configuration&quot;: [
          {
            &quot;name&quot; : &quot;token&quot;,
            &quot;value&quot; :&quot;1234567890&quot;
          }
        ]
      },
      {
        &quot;provider&quot;: &quot;phone&quot;,
        &quot;contact&quot;: &quot;123456789&quot;,
        &quot;configuration&quot;: [
          {
            &quot;name&quot; : &quot;access_token&quot;,
            &quot;value&quot; :&quot;987654321&quot;
          }
        ]
      }
    ]
  }
  </code></pre>
  <p><strong>Code:</strong></p>
  <pre><code>app.post('/channelEnterprise', (req, res) =&gt; {
      var output = [];
      checkEnterpriseByName(req.body.enterpriseName, knex).then((exist) =&gt; {
          if (exist) {
              req.body.channels.forEach(channel =&gt; {
                  addChannel(req.body.enterpriseName, channel, knex).then((channelEnterpriseId) =&gt; {
                      output.push({'provider' : channel.provider,
                                   'Id': channelEnterpriseId[0],
                                   'result': 'ok'
                      })                  
                      res.json(output)                    
                  });             
              });             
          }else{
              res.status(500).send({ error: 'Enterprise' + req.body.enterpriseName + ' does not exist. Try to create previous the enterprise and then add the channel' });
          }   
      })
  })
  </code></pre>
  <p><strong>Goal:</strong>
  The goal is to run <em>res.json(output)</em> only when the foreach has been finished with something like this:</p>
  <pre><code>[
      {
          &quot;provider&quot;: &quot;mail&quot;,
          &quot;Id&quot;: 15,
          &quot;result&quot;: &quot;ok&quot;
      },
      {
          &quot;provider&quot;: &quot;phone&quot;,
          &quot;Id&quot;: 16,
          &quot;result&quot;: &quot;ok&quot;
      }
  
  ]
  </code></pre>