即使使用异步后,nodejs也返回空数组,等待

时间:2020-01-28 06:06:42

标签: javascript node.js neo4j

我正在尝试为电影推荐网站生成类似电影的列表,但是返回的最终数组为空。请参考下面的代码和控制台输出。

const getRecommendations = async (email) => {
    const randomSeedIds = await getRandomSeed(email);
    console.log(randomSeedIds);
    try {
        const movies = []; //the array im returning
        randomSeedIds.forEach(async id => {
            const simMovies = await movieApi.getSimilar(id, 5);// generates list of similar movies
            console.log(simMovies);
            simMovies.forEach(movie => movies.push(movie));// pushing similar movies to movies arr
        });
        console.log(movies);
        return movies;
    } catch (error) {
        console.log(error);
    }
}

控制台输出:您可以看到数据库完美地返回了记录。

[ '0109830', '1375666' ] // movies from which im generating recommendations

[] // array im trying to return (why is this empty ?) 

[ { title: 'Insomnia',
    imdbId: '0278504',
    poster: '/images/278504.jpg' },
  { title: 'Patlabor: The Movie (Kidô keisatsu patorebâ: The Movie)',
    imdbId: '0100339',
    poster: '/images/100339.jpg' },
  { title: 'Dark Knight Rises, The',
    imdbId: '1345836',
    poster: '/images/1345836.jpg' },
]// similar movies of seed movie1

[ { title: 'Train of Life (Train de vie)',
    imdbId: '0170705',
    poster: '/images/170705.jpg' },
  { title: 'Tiger and the Snow, The (La tigre e la neve)',
    imdbId: '0419198',
    poster: '/images/419198.jpg' },
  { title: 'Life is a Miracle (Zivot je cudo)',
    imdbId: '0322420',
    poster: '/images/322420.jpg' },
 ]// similar movies of seed2

0 个答案:

没有答案