mardi 27 octobre 2020

control-flow issue multiple if-statements

I have a piece of code that works fine in dev, but isn't scaling.

The goal is to: (1) find MongoDB doc, (2) if there is a document, push into array, (3) if the loop is finished, return next()

Code:

//Grab a list of all the active users
for(let i=0; i<res.locals.masterPhaseArray.length; i++){
    
    User.find({team_oid: res.locals.masterPhaseArray[i].team_oid}, {_id: 0, email: 1, firstname: 1}).then(doc => {

        if(doc[0]){
            liveUsers.push(doc[0])
        }

        if(res.locals.masterPhaseArray.length == i+1){
            res.locals.liveUsers = liveUsers
            return next()
        }
    });
}

The issue is that when doc is long liveUsers.push() does not complete before return next() is reached, and so the incomplete document is sent.

How can I make sure that liveUsers.push() is finished before it reaches the next if statement?

Aucun commentaire:

Enregistrer un commentaire