0
router.post('/createGroups',async (req)=>{
    const {leagueID,teams} = req.body
    await Promise.all(teams.map((group,rank)=>{
        group.map(async(t,index)=>{
            if(index === 0){
                console.log(index,rank,t)
                const createdGroup = new Group({league:leagueID, group:{team:t}, rank:rank+1})
                return await createdGroup.save()
            }else{
                console.log(index,rank,t)
                return await Group.findOneAndUpdate(
                    {league:req.body.leagueID, rank:rank+1},
                    {$push:{
                        group:{
                            $each:[{team:t}]
                        }
                    }
                })
            }
        })
    }))
})

I am trying to loop over group, take the 1st element, insert a document, wait until the document is inserted, then update the same document to add the remaining elements into the nested array (group).

Basically, I want it to wait until each promise is resolved before proceeding with next item.

I am not sure about my approach so suggestions for how I can achieve this are welcome?

Zizo
  • 19
  • 3
  • Use a for loop instead. It will await each promise and execute them in sequence. (also, in general, please use .forEach and not .map in a case like this) –  Mar 03 '22 at 23:45
  • Duplicate: [Resolve promises one after another (i.e. in sequence)?](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) –  Mar 03 '22 at 23:47

0 Answers0