I have an array of ids and I am trying to map through this array to create a new array of movie objects which is in my database.
my code looks like this...
const movieIds = foundDirector.movies;
const movies = movieIds.map(async (id) => {
await Movie.findById(id);
});
The code above doesn't work. I am able to find a movie and see that data from within the map function but when I print movies to the console I get an array with empty objects.
I then decided to do this instead and it works.
const movieIds = foundDirector.movies;
let movies = [];
for (let i = 0; i < movieIds.length; i++) {
const movie = await Movie.findById(movieIds[i]);
movies.push(movie);
}
I'm not happy with the solution. I obviously am having issues understanding how promises work in JavaScript and using async/await
has been easy enough for now but I don't want to rely on it.
as an example I tried doing something like...
const movieIds = foundDirector.movies;
let movies = [];
for (let i = 0; i < movieIds.length; i++) {
const movie = Movie.findById(movieIds[i]).then((data) => data);
movies.push(movie);
}
const allMovies = Promise.all(movies).then((values) => values);
I noticed that after printing movies to the console I was getting an array of pending promises I tried using const allMovies = Promise.all(movies).then((values) => values);
but allMovies
still just is a pending promise.
Can anyone please explain what is going on here, and how can I achieve this with a map function rather than a for loop.