title: Nested forEach and Asynchronity
body: <p>I am currently working on an authorization functionality for a node.js website. I am working with Sequelize as an ORM and Passport as a login manager. To enable authorization functionality I want to add an authorization-name array (just strings) to the request Object (i.e. <code>["manageDelete", "manageAdd", "userManage"]</code>). I want to do that in the <code>passport.deserializeUser()</code> method.  </p>
  
  <p>Here is some additional information:</p>
  
  <p>The authorizations are stored in a MySQL database table called <code>authorizations</code>. This table is associated to another table called <code>roles</code> in a <code>n to m</code> relation (what I ultimately want to achieve is to bundle the authorizations together to make managing the authorizations more easy).</p>
  
  <p>I have huge problems with async code because this topic is very new to me. My code to accumulate all the authorizations of the roles of a user is this:</p>
  
  <pre><code>passport.deserializeUser(function (id, done) {
    var currUser;
    models.User.findById(id)
    .then((user) =&gt; {
      currUser = user;
      //gets array of associated roles for this user
      return user.getRoles(); 
    })
    .then((roles) =&gt; {
      var authArr = [];
      roles.forEach((role) =&gt; {
        //gets array of associated authorizations for this role
        role.getAuthorizations().then((auths) =&gt; {
          auths.forEach((auth) =&gt; {
            authArr.push(auth.name);
          });
        });
      });
      return authArr;        
    })
    .done((authArr) =&gt; {
      done(null, {user: currUser, authArr: authArr});
    });
  });
  </code></pre>
  
  <p>I know that because of the asychronosity the <code>done()</code> method is called before any of the promises are resolved, but I can not find any way to prevent that from happening. I have tried countless different patterns (e.g this: <a href="https://www.joezimjs.com/javascript/patterns-asynchronous-programming-promises/" rel="nofollow">https://www.joezimjs.com/javascript/patterns-asynchronous-programming-promises/</a>, or async.js') but I can not get it to work.</p>
  
  <p>What am I doing wrong? Is there any solution without using any additional modules? Help would be appreciated a lot. Thanks in advance!</p>