javascript - 使用 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
解决方案
如果您检测外部请求可能会有所帮助。但是,您不能让外部服务更快地响应。
您可以做的是在您的服务器上添加一些缓存。您引用的数据不太可能经常更改。即使您只缓存了 15 分钟的热门电影目标,它几乎肯定会有所帮助。
推荐阅读
- python - 如何修复 AttributeError:'NoneType' 对象在此特定代码中没有属性 'strip'?
- bash - 如何在 Mac OS X 中使用 Bash 将 +1 添加到纪元时间?
- ios - Mapkit 显示格式如下:城市,州,国家
- c++ - void 后面的 * 符号是什么意思。添加 void* 对函数有什么作用?
- python - ImportError:无法从部分初始化的模块“openpyxl”导入名称“工作簿”
- javascript - 指针事件 API 不一致
- php - 意外警报打开导致 Behat/Mink 测试出错
- python - python excel减去2个工作表
- git - 如何找到从哪个 github 分支标签创建的?
- bash - 分配变量时尝试在其中添加两个变量