title: Node.js Sequalize creating new rows in forEach loop
body: <p>I'm trying to create new rows in the database using Sequalize ORM. I receive an array of collections from <code>req.query.collections</code>. For each of those collections I need to create a new <code>userCollection</code>. If none <code>userCollection</code>s were created, I wanna respond with internal server error (line 41), otherwise return an array of objects with newly created <code>userCollections</code>.</p>
  
  <p>The problem is, I keep getting an internal server error when I make test requests from Postman. When I check my database, I see that those <code>userCollections</code> were created, so no error occurred.</p>
  
  <p>I know why this happens: because <code>userCollection.build({ stuff }).save()</code> returns a promise. So when I try to console.log <code>userCollections</code> from within <code>.then()</code> statement, I get an array with a newly created collections, just like I should. But by that time server has already responded with internal server error.</p>
  
  <p>Here's my function code:</p>
  
  <pre><code>exports.addCollections = async (req, res, next) =&gt; {
      const libraryId = req.params.libraryId;
      const collections = req.query.collections;
  
      if (!collections)
          next(Boom.forbidden());
  
      const userCollections = [];
  
      collections.forEach(async (collectionId, index) =&gt; {
          const collection = await Collection.findByPk(collectionId);
  
          if (!collection)
              return next(Boom.notFound());
  
          userCollection.build({
              user_id: req.user.id,
              library_id: libraryId,
              public_collection_id: collection.id,
              title: collection.title,
              description: collection.description
          })
              .save()
              .then(newUserCollection =&gt; {
                  userCollections.push(newUserCollection.get({ plain: true }));
  
                  // should be printed first, but comes second
                  // prints out the array with newly created record
                  console.log(userCollections);
              })
              .catch(error =&gt; {
                  console.log(error);
              });
      });
  
      // should be printed second, but comes first
      // prints out empty array
      console.log(userCollections);
  
      if (userCollections.length === 0) {
          next(Boom.internal());
      }
  
      res.json(userCollections);
  }
  </code></pre>