簡體   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