[英]How can I store the data I get from a Promise back into an object with the same key it came from?
A bit of an ambiguous title, but I'll explain... 标题有点含糊,但我会解释...
I am making a fetch
call to 4 different URLs from The Movie Database . 我想提出一个
fetch
调用从电影数据库 4周不同的网址。 Once these fetch calls retrieve the data, it will then setState
and update my initial state. 一旦这些获取调用检索数据时,它会那么
setState
和更新我的初始状态。 However, I don't want my page to load until all of the data is retrieved, so I am using Promise.all
(or attempting to). 但是,在检索所有数据之前,我不希望加载页面,因此我正在使用
Promise.all
(或尝试使用)。
My code so far... 到目前为止,我的代码...
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);
Now what I have here is an array ( promiseArr
) of objects that have the correct key with the correct Promise
stored inside of them. 现在,我在这里有了一个对象数组(
promiseArr
),这些对象具有正确的密钥,并且内部存储了正确的Promise
。
My next plan was going to be to call Promise.all
on them, but I need an array of promises. 我的下一个计划是将
Promise.all
放在他们身上,但我需要一系列承诺。 After I get the actual data back from the URL calls, I wanted to store them back in the object, to the correct corresponding key? 从URL调用中获取实际数据后,我想将它们存储回对象中,以正确的对应键?
I've been stuck at this part for a couple hours now...any tips would be appreciated! 我已经在这部分上停留了几个小时...任何提示将不胜感激!
You can use async/await
and Object.entries()
to convert a JavaScript plain object to an array of arrays of key, value pairs 您可以使用
async/await
和Object.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)
}
}
})()
Don't call then when adding to promise array. 添加到Promise数组时,请勿调用。 Instead call it in promise all
取而代之
const trending = fetch(trending);
...
Promise.all([trending, topRated, nowplaying, upcoming]).then(([trending, topRated, nowplaying, upcoming]) => {
movies.trending = trending.json();
....
});
You could just also store the promises themselves in another array. 您也可以将承诺本身存储在另一个数组中。
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); });
If that is not feasible, you can do something like: Promise.all(promiseArr.map(obj => Object.values(obj)[0]))
如果这不可行,则可以执行以下操作:
Promise.all(promiseArr.map(obj => Object.values(obj)[0]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.