Search code examples
javascriptasynchronousasync-awaitmern

Handling Async JS


I'm getting the movie record from the database and the movie record have a list of IDs of the actors in the movie so I'm sending another request to the database to get the actors and then I'm going to replace the list of IDs with the list of the actors. and this code works but of course it's bad because of setTimeout so how can I execute the code inside setTimeout after the code above finishes

const getMovie = async (req, res) => {
  
    let actors  = [];

    Movie.findById(req.params.id)
    .then(movie => {
        if (movie == null) res.json('This movie does not exist')
        
        else 
        {
           
            movie.Actors.forEach(element => {
                Actor.findById(element)
                .then((a) => {
                    actors.push(a);
                })
            });

            setTimeout(() => {
                movie.Actors = actors;
                res.json(movie);
            }, 1000);

        }
    })
    .catch(err => res.status(400).json(`Error: ${err}`))

}

I tried to use Promise but it didn't work, but of course I'm an imposter so I may have implemented it in a wrong way


Solution

  • Here's how I would integrate that logic into your existing promise flow:

    Promise.all(
      movie.Actors.map(element => Actor.findById(element))
    ).then(actors => {
      movie.Actors = actors;
      res.json(movie);
    });