首页 > 解决方案 > 使用 tmdb api 加载页面非常缓慢

问题描述

所以我正在尝试使用 tmdb api 获取热门电影和电视节目,然后我尝试获取它们的 imdb id,但是页面在几秒钟内呈现,这太慢了我想知道是否有办法优化我的代码或者如果问题出在 api 调用中

router.get('/',redirect,(req,res)=>{
    const option={
        url:"https://api.themoviedb.org/3/trending/movie/week?api_key=9bde952e56ff27d1016ff6144cbf27c9",
        json:true
    };
    const optiontv={
        url:"https://api.themoviedb.org/3/trending/tv/week?api_key=9bde952e56ff27d1016ff6144cbf27c9",
        json:true
    }
    request(option).then(resp=>{
        let trending_id=[];
        trending_id=resp.results.map((movie)=>{
            const optionid={
                url:`https://api.themoviedb.org/3/movie/${movie.id}/external_ids?api_key=9bde952e56ff27d1016ff6144cbf27c9`,
                json:true
            }
            return request(optionid).then(respid=>{
                return {id:respid.imdb_id,poster:`https://image.tmdb.org/t/p/w600_and_h900_bestv2${movie.poster_path}`};
            }).catch(err=>console.log(err));
        })
        request(optiontv).then(resptv=>{
            let trending_id_tv=[];
            trending_id_tv=resptv.results.map((tv)=>{
                const optionid_tv={
                    url:`https://api.themoviedb.org/3/tv/${tv.id}/external_ids?api_key=9bde952e56ff27d1016ff6144cbf27c9&language=en-US`,
                    json:true
                }
                return request(optionid_tv).then(respid_tv=>{
                    return {id:respid_tv.imdb_id,poster:`https://image.tmdb.org/t/p/w600_and_h900_bestv2${tv.poster_path}`};
                })
            });
            Promise.all(trending_id).then((values_movie)=>{
                Promise.all(trending_id_tv).then(values=>{
                    const user=req.session.name.split(' ')[0];
                    res.render('homepage',{name:user,imdbid_poster:values_movie,imdb_poster_tv:values});
                }).catch(err=>console.log(err));
            }).catch(err=>console.log(err));
        }).catch(err=>console.log(err));
    });
});

有时最多需要 5 秒来呈现页面

GET /home 304 5820.419 ms - -
GET /public/stylesheets/bootstrap.min.css 304 4.617 ms - -
GET /public/stylesheets/mdb.min.css 304 4.719 ms - -
GET /public/stylesheets/header.css 304 4.955 ms - -
GET /public/stylesheets/footer.css 304 4.406 ms - -
GET /public/stylesheets/flickity.css 304 5.950 ms - -
GET /public/stylesheets/homepage.css 304 5.407 ms - -
GET /public/javascripts/homepage.js 304 2.590 ms - -
GET /public/javascripts/header.js 304 5.542 ms - -
GET /public/javascripts/flickity.pkgd.min.js 304 3.179 ms - -
GET /public/images/logo.png 304 3.955 ms - -
GET /public/images/Recify%20background6.jpg 304 2.729 ms - -
GET /public/images/FavIcon.png 200 2.226 ms - 99291

标签: javascriptnode.jsapi

解决方案


如果您检测外部请求可能会有所帮助。但是,您不能让外部服务更快地响应。

您可以做的是在您的服务器上添加一些缓存。您引用的数据不太可能经常更改。即使您只缓存了 15 分钟的热门电影目标,它几乎肯定会有所帮助。


推荐阅读