繁体   English   中英

如何将从Promise中获得的数据存储到具有相同密钥的对象中?

[英]How can I store the data I get from a Promise back into an object with the same key it came from?

标题有点含糊,但我会解释...

我想提出一个fetch调用从电影数据库 4周不同的网址。 一旦这些获取调用检索数据时,它会那么setState和更新我的初始状态。 但是,在检索所有数据之前,我不希望加载页面,因此我正在使用Promise.all (或尝试使用)。

到目前为止,我的代码...

  state = {
    movies: {
      trending: {},
      topRated: {},
      nowPlaying: {},
      upcoming: {},
     },
  };




 const allMovieURLs = {
      trending: `https://api.themoviedb.org/3/trending/all/day?api_key=${API_KEY}`,
      topRated: `https://api.themoviedb.org/3/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`,
      nowPlaying: `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1`,
      upcoming: `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`
    };

//initialize an empty array to Promise.all on
const promiseArr = [];

//loop through movie URLs, call fetch + json()
for (const movies in allMovieURLs) {
  //create an object that directly describes the data you get back from the url with a key
  const obj = {
    [movies]: fetch(allMovieURLs[movies]).then(res => res.json())
  };
  //push that object into an array so you can use Promise.all
  promiseArr.push(obj);

现在,我在这里有了一个对象数组( promiseArr ),这些对象具有正确的密钥,并且内部存储了正确的Promise

我的下一个计划是将Promise.all放在他们身上,但我需要一系列承诺。 从URL调用中获取实际数据后,我想将它们存储回对象中,以正确的对应键?

我已经在这部分上停留了几个小时...任何提示将不胜感激!

您可以使用async/awaitObject.entries()将JavaScript纯对象转换为键,值对数组的数组

(async() => {
  for (const [movie, url] of Object.entries(allMovieURLs)) {
    try {
      allMovieURLs[movie] = await fetch(url).then(res => res.json())
                                  .catch(e => {throw e})
    } catch(e) {
        console.error(e)
    }
  }
})()

添加到Promise数组时,请勿调用。 取而代之

const trending = fetch(trending);
...

Promise.all([trending, topRated, nowplaying, upcoming]).then(([trending, topRated, nowplaying, upcoming]) => {
   movies.trending = trending.json();
   ....
});

您也可以将承诺本身存储在另一个数组中。

 function fetch() { var time = Math.random() * 1E3; return new Promise(function (res, rej) { setTimeout(function () { res(time); }, time); }); } const API_KEY = ""; const allMovieURLs = { trending: `https://api.themoviedb.org/3/trending/all/day?api_key=${API_KEY}`, topRated: `https://api.themoviedb.org/3/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`, nowPlaying: `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1`, upcoming: `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1` }; const promiseArr = []; const promises = []; for (const movies in allMovieURLs) { const obj = { [movies]: undefined }; promises.push(fetch(allMovieURLs[movies]).then(res => obj[movies] = res)); promiseArr.push(obj); } Promise.all(promises).then(function () { console.log(promiseArr); }); 

如果这不可行,则可以执行以下操作: Promise.all(promiseArr.map(obj => Object.values(obj)[0]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM