title: Promises inside for loops / promise.all, using psql (pg-promise) in node
body: <p>Hello I am new to Promises and am stuck on how to wait for all promises within a for loop to resolve before going to the next then(). I have seen a couple of promise.all examples, but it wasn't clear to me how to adapt them for my the following code. It currently goes to the next then() after the for loop and resolves before the for loop is complete. Any help is appreciated!</p>
  
  <p>I am using <a href="https://www.npmjs.com/package/pg-promise" rel="nofollow">pg-promise</a> (psql with promises).</p>
  
  <p><strong>Original code:</strong></p>
  
  <pre><code>function getTeamMembers(aTeam) {
      let promise = new Promise(function(resolve, reject) {
        db.getTeamMembers(aTeam.tid) //return sql results rows
          .then(function(rows){
            for(let i=0; i&lt;rows.length; ++i) { //loop through each result row
              getUserByUsername(rows[i].username)
                .then(function(cfUser) { //add user from row to aTeam object                    
                  aTeam.addMember(cfUser);
                })
                .catch(function(e) {
                  reject(e);
                });
            }
          })
          .then(function(){
            console.log(aTeam); //confirm added properly
            resolve(aTeam); //resolve object
          })
          .catch(function(e) {
            console.log('addMemberToTeamByUsername: '+e.stack);
            reject(e);
          });
      });
      return promise;
    }
  </code></pre>