0

My function is being triggered by a post request.

I am sending an array of ids from the front end and using forEach to go over every element and send an api call to get data back and push that data into a new array.

I cant seem to access the data outside of the loop. ex. I want to res.json(array) but array shows empty. When I --> .then(participants => console.log({"sid": participants.sid})) I see the logs just fine

const listParticipants = async (req, res) => {
    const { subActServiceSid, subActAuthToken, convoServiceSid} = req.user
    const subClient = require('twilio')(subActServiceSid, subActAuthToken)
    const { data } = req.body
    const array = []
    await data.forEach(convo => {
       subClient.conversations.services(convoServiceSid)
      .conversations(convo)
      .participants
      .list({limit: 20})
      .then(participants => array.push({"sid": participants.sid}));
       
    })
    res.json(array) // this is showing empty array....
 }

this is the const {data} = req.body
[
"CH01db9e1427994dg",
"CH1b1cc2b8f5534gb",
"CH34c27e8ff76e403",
"CH363665d704ab48f",
"CH410e8d086310443",
"CH4d2ac9670d2d413",
"CH4e1ef59ac99e48c",
]
AmandaConda
  • 223
  • 3
  • 13
  • 1
    This is pretty much exactly why Promise.all() exists. Use the "reading in parallel" section of the accepted answer in the dupe. –  Nov 04 '21 at 20:53
  • Thanks Chris, That ended up working for me! Thanks for pointing me in the right direction – AmandaConda Nov 04 '21 at 21:08

0 Answers0