Ron I Ron I - 1 month ago 34
Node.js Question

Promises inside for loops / promise.all, using psql (pg-promise) in node

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!

I am using pg-promise (psql with promises).

Original 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<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;
}

Answer

Firstly, avoid the Promise Constructor anti-pattern. clearly db.getTeamMemebers returns a Promise, so no need to wrap your code in a new Promise

you would use Promise.all to wait for the getUserByUsername calls - Array#map is useful for this

like so:

function getTeamMembers(aTeam) {
    return db.getTeamMembers(aTeam.tid) //return sql results rows
    .then(function(rows) {
        return Promise.all(rows.map(function(row) {
            return getUserByUsername(row.username)
            .then(function(cfUser) { //add user from row to aTeam object                    
                aTeam.addMember(cfUser);
            });
        }));
    })
    .then(function() {
        console.log(aTeam); //confirm added properly
        return aTeam;
    })
    .catch(function(e) {
        console.log('addMemberToTeamByUsername: ' + e.stack);
        throw e;
    });
}
Comments