I'm trying to make an api call several times inide a For:
const myPromise = new Promise(function(resolve, reject) {
// code here
for (let i = 0; i < recommendedMovies.length; i++) {
tmdb.genre.movies(
recommendedMovies[i].id,
randomNumber,
(err, response) => {
if (!err) {
finalMovies.push(response.results);
resolve(finalMovies)
} else {
reject('error')
}
}
);
}
});
as you can see, i'm pushing each call result into an array called finalMovies, and then trying to return the result as follow:
myPromise
.then(function whenOk(response) {
res.json(response)
})
.catch(function notOk(err) {
console.log(err);
});
The problem is that i'm only getting the array with the first call in it.
How can i change my code so i can wait myPromise to complete the loop and then return the array?.
Thanks!