0

I'm having some trouble figuring out what I need to add to allow for the get requests to finish and store the responses in twoDeeArray so I can pass them to the html page. Currently the console.log(twoDeeArray) at the bottom is returning an empty array. I thought Promise.all would solve my problem and though it has fixed some issues I was having previously I'm still confused as to why the array is empty.

I don't think my schema info is necessary but just in case. I have two models, User and DoubleFeature. User contains a field called doublefeatures which stores tuples of movie ids that the user created a DoubleFeature for. It's a many to one relationship.

router.get('/:username', (req, res) => {
    const username = req.params.username;
    const doublefeatures = req.user.doublefeatures;
    const twoDeeArray = [];
    for (i = 0; i < doublefeatures.length; i++) {
        DoubleFeature.findById(doublefeatures[i]).then(doublefeature => {
            function getMovieOne() {
                return axios.get(movieURL + doublefeature.movie_one_id + '?api_key=' + key);
            };

            function getMovieTwo() {
                return axios.get(movieURL + doublefeature.movie_two_id + '?api_key=' + key);
            };

            Promise.all([getMovieOne(), getMovieTwo()])
                .then(results => {
                    const movie_one = results[0].data;
                    const movie_two = results[1].data;
                    twoDeeArray.push([movie_one.title, movie_two.title]);
                });
        });
    };
    console.log(twoDeeArray);
    res.render('users', {
        'username': username
    });
});
  • the short of it is that `twoDeeArray.push([movie_one.title, movie_two.title]);` happens AFTER `console.log(twoDeeArray);` - because of asynchrony – Jaromanda X Sep 18 '20 at 01:34
  • Right, but what exactly would I need to add or change for the array to push before ```console.log();``` – Arsalan Yusuf Sep 18 '20 at 01:38
  • I was able to solve the problem with someone's help. I rewrote my code so it was neater and worked with `async/await`. An `async function` outside the for loop was needed so it finished executing the for loop and then rendered the page. [Here's a link to the code](https://pastebin.com/5vPj9Vji) – Arsalan Yusuf Sep 19 '20 at 01:32

0 Answers0