我正在尝试使用Promise.all从电影数据库中一次获取多个数据对象。在遍历fetch调用的所有结果并在数据的每一位上使用.json()之后,我尝试将其记录到控制台。但是,我得到的不是带有数据的对象数组,而是一个Promises数组。嵌套在Promise中,我可以看到我的数据,但显然缺少用于拥有数据对象数组的步骤,而不仅仅是Promises

我在这里想念什么?

 //store movie API URLs into meaningful variables
    const trending = `https://api.themoviedb.org/3/trending/all/day?api_key=${API_KEY}`;
    const topRated = `https://api.themoviedb.org/3/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`;
    const nowPlaying = `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1`;
    const upcoming = `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`;
    //create an array of urls to fetch data from
    const allMovieURLs = [trending, topRated, nowPlaying, upcoming];
    const promiseURLs = allMovieURLs.map(url => fetch(url));
    Promise.all(promiseURLs)
      .then(responses => responses.map(url => url.json()))
      .then(dataArr => console.log(dataArr));
  };

最佳答案

您的.then(responses => responses.map(url => url.json()))解析为一个Promises数组,因此,如果要等待所有解析,则需要再次调用Promise.all:

Promise.all(promiseURLs)
  .then(responses => Promise.all(responses.map(url => url.json())))
  .then(dataArr => console.log(dataArr));

或者,您可以考虑只使用一个Promise.all,并使用每个URL fetchjson,这样在脚本执行过程中某些项目就不会闲置:
const allMovieURLs = [trending, topRated, nowPlaying, upcoming];
const promiseURLs = allMovieURLs.map(url => fetch(url).then(res => res.json()));
Promise.all(promiseURLs)
  .then(dataArr => console.log(dataArr));

10-07 14:54
查看更多