标题有点含糊,但我会解释一下......
我正在对电影数据库中的 4 个不同 URL 进行 fetch
调用。
一旦这些 fetch 调用检索到数据,它将 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
),这些对象具有正确的 key ,并且其中存储了正确的 Promise
。
我的下一个计划是对它们调用Promise.all
,但我需要一组 promise 。当我从 URL 调用中获取实际数据后,我想将它们存储回对象中,存储到正确的对应键中?
我已经在这部分卡了几个小时了......任何提示将不胜感激!
最佳答案
您可以使用 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)
}
}
})()
关于javascript - 如何将从 Promise 获得的数据存储回具有与其来源相同的 key 的对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861581/