0

Express router is not awaiting my forEach loop and sends the old unmanipulated object as a response instead of the new manipulated data.

Here I am using Sequalize as my ORM.

router.get('/', async (req,res) => {
    try {
        let trainings = await db.Training.findAll();
        let locations = await db.Location.findAll();

        await locations.forEach(location => {
            trainings.forEach(training => {
                if(location.trainingId == training.id){
                    training["location"] = location
                }
            })
        })

        res.status(200).json({
            training:trainings
        })
    } catch(err) {
        console.log(err);
        res.status(404).json({
            message : err
        })
    }
})
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49

1 Answers1

0

Basically you are using the await keyword against a synchronous process which is

locations.forEach(location => {
        trainings.forEach(training => {
            if(location.trainingId == training.id){
                training["location"] = location
            }
        })
    })

These lines of code doesn't return any promise or behave like a promise. So one solution can be having a function

function modify(trainings,locations){
    return new Promise((resolve,reject)=>{
        locations.forEach(location => {
        trainings.forEach(training => {
            if(location.trainingId == training.id){
                training["location"] = location
            }
        })
        })
        resolve('done')
    })
}

then have it like this

let trainings = await db.Training.findAll();
let locations = await db.Location.findAll();
await modify(trainings,locations)

or you can simply remove the await keyword from your current state of code.