我正在使用 TMDB API并且在让响应按顺序传播到该州时遇到问题。
我正在绘制 3 个列表。在每个列表中,我都有电影,我也在映射这些电影以获取我的 TMDB ID。从那里,我得到我需要的值并设置状态。在理想的世界中,状态将按照我用 map 函数调用它的顺序设置。
由于 API 仅允许每个请求使用 1 个 ID,因此这是我的解决方案。我知道我在这里遗漏了一些明显的东西,但是对此的任何指导都将不胜感激!
fetchMoviesFromTMDB = async () => {
const TMDb_access_key = TMDB_API_KEY;
await this.props.dashboard.items[0].fields.lists.map(async list =>
list.fields.movies.map(async (movie, index) => {
try {
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/movie/${
movie.fields.tmDbMovieId
}?api_key=${TMDb_access_key}&append_to_response=credits,releases`
);
const TMDB = await tmdbRes.json();
await this.setState({
allMovies: [
...this.state.allMovies,
[
movie.fields.path,
TMDB.poster_path,
movie.fields.movieTitle,
index,
],
],
});
} catch (err) {
console.log(err);
}
})
);
};
最佳答案
你会想看看Promise.all
,这正是您想要的,按顺序执行一系列 promise 。
只需将你的数组发送给它,如果你想用它做任何其他事情,然后等待它的结果:
await Promise.all(this.props.dashboard.items[0].fields.lists.map(async list =>
list.fields.movies.map(async (movie, index) => {
try {
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/movie/${
movie.fields.tmDbMovieId
}?api_key=${TMDb_access_key}&append_to_response=credits,releases`
);
const TMDB = await tmdbRes.json();
await this.setState({
allMovies: [
...this.state.allMovies,
[
movie.fields.path,
TMDB.poster_path,
movie.fields.movieTitle,
index,
],
],
});
} catch (err) {
console.log(err);
}
})
));
关于javascript - 在未按顺序执行的 JavaScript 映射函数中使用 Async/Await 和 Fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206340/