node.js tmdbv3 api 遍历页面搜索结果

node.js tmdbv3 api loop through pages search results

我已经编写了一些代码来构建我的电影 collection 的数据库,我将 node.js 与 api tmdbv3 一起使用,但我遇到了一个问题,其中 tmdb api 是 return 分页结果。我正在尝试循环页面,但似乎只有 return 最后一个 for 循环的结果。

我尝试设置 promise、async、await,但每次都不知道在哪里放什么和 运行 错误。

tmdb.search.movie('fast & furious', (err, res) => {
      // console.log(res.total_pages);
      totalPages = res.total_pages;
      console.log(totalPages);
      for (i = 1; i <= totalPages; i++) {
        tmdb.search.movie(release, i, (err, res) => {
          jsonMovie = res.results;
          console.log('page: ' + i);
          console.log(jsonMovie[0].title);
          if (jsonMovie.length > 0) {
            io.emit('giveMovieToProcess', jsonMovie);

          } else {
            io.emit('giveMovieToProcess', 'No search results');
          }
        });
      }
    });

这就是我得到的

Fast & Furious
20
page: 21
Still Too Fast to Race
page: 21
LOCAL58 - You Are On The Fastest Available Route
page: 21
The Fastest Gun Alive
page: 21
Fast Lane to Vegas
page: 21
Too Fast For Food
page: 21
Eine fast perfekte Liebe
page: 21
Fast Trip, Long Drop
page: 21
Faster
page: 21
Faster Foster
page: 21
Fast, Cheap & Out of Control
page: 21
Adrenaline Ride: Fast Times
page: 21
Bling
page: 21
Action Man
page: 21
After the Fox
page: 21
Fast Friday
page: 21
Jillian Michaels: Kickbox FastFix Workout 1
page: 21
Picture Perfect
page: 21
Two Fast - The Journey of Triathlon Legends
page: 21
Born to Race
page: 21
Fast & Furious Presents: Hobbs & Shaw

我最终意识到匿名函数是一个回调,大声笑,并创建了一个递归函数,如果它不是最后一页,它会在回调中不断调用自身,同时将结果添加到 JSON是我在客户端处理的。我知道可能有更短更有效的方法来实现这一点。

function requestTMDB(release, parentDir) {
  console.log('release = ' + release);
  let totalPages;
  let jsonCollection = [];
  if (release === '') {
    io.emit('giveMovieToProcess', 'No search results');
    return;
  }
  tmdb.search.movie(release, (err, res) => {
    console.log(res.total_pages);
    totalPages = res.total_pages;
    // console.log(totalPages);
    let pageNum = 1;
    lastCall();

    function lastCall() {
      tmdb.search.movie(release, pageNum, (err, res) => {
        jsonCollection.push(res.results);
        if (res.page < totalPages) {
          console.log('calling page ' + pageNum + ' of ' + totalPages);
          lastCall();
        } else {
          // console.log('finished calling');
          console.log('jsonCollection.length ' + jsonCollection.length);
          if (res.total_results === 0) {
            requestTMDB(parentDir, '');
          } else {
            io.emit('jsonCollection', jsonCollection);
          }
        }
      });
      pageNum++;
    }
  });
}