gpt4 book ai didi

javascript - 如何等待 .map() 在继续下一行代码之前完成执行

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:34 25 4
gpt4 key购买 nike

如何在更新状态之前等待所有帖子被推送到帖子数组?

我必须遍历一组帖子 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

关于javascript - 如何等待 .map() 在继续下一行代码之前完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47669849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com