[英]How to wait for .map() to finish executing before continuing on to next lines of code
如何在更新状态之前等待所有帖子被推送到帖子数组?
我不得不遍历一系列帖子 ID 以获取 HackerNews 上的热门帖子,然后将所有这些 ID 转换为单个帖子链接,并希望将来自单个帖子链接的数据存储在一个数组中,以便我可以遍历该数组进行渲染它在 DOM 中。
import React, {Component} from 'react'; import axios from 'axios'; import Post from './Post'; class ContentWrapper extends Component { constructor(props){ super(props); this.state = { posts: [] } } componentDidMount(){ const topStories = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'; // `https://hacker-news.firebaseio.com/v0/item/.json?print=pretty` axios(topStories).then(res => { const posts = []; res.data.map(val => { const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`; return axios.get(url).then(res => { posts.push(res.data); }).then(res => this.setState({posts: res})); }); }); } render() { const posts = this.state.posts.map((val, i) => { return <Post key={i} title={val.title} author={val.by} /> }); return ( <div className="content-wrapper"> <h2>{this.props.currentSource}</h2> {posts} </div> ) } } export default ContentWrapper;
您将不得不使用Promise.all
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
const topStories =
"https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
axios(topStories).then(res => {
const posts = [];
const requests = res.data.map(val => {
const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
return axios.get(url).then(res => {
posts.push(res.data);
});
});
// Wait for all requests, and then setState
return Promise.all(requests).then(() => {
this.setState({
posts
});
});
});
在这里测试: https : //runkit.com/embed/8pac53dhmy2y
更新还有Promise.allSettled
如果promise 数组有任何错误,它在某些情况下可能会更好; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.