我正在使用 redux-thunk
来管理一些副作用。问题如下。在我的 react 组件中的某个地方,我有一个函数,负责在组件安装或获取新 Prop 后获取所有必要的数据,即 fetchRequiredData()
。
在fetchRequiredData()
中,我循环遍历一个数组,因为每个键都需要获取一些数据。我需要能够有一个总体 promise ,只有当 .map()
内的 promise 得到解决时,该 promise 才会得到解决。如果我没有这个,页面就会遇到麻烦,因为它试图渲染它不能渲染的东西。
简化的代码示例
export const fetchRequiredData = (requiredAccounts) => (dispatch) => {
// How to wrap the promises inside the .map() into 1 "big" promise?
requiredAccounts.map(account => {
dispatch(fetchAccount(account)); // Returns a promise
});
}
在我的组件中,我应该能够执行以下操作
class Accounts extends Component {
constructor(props) {
super(props);
this.state = {
pending: true;
}
}
componentDidMount() {
this.setState({pending: true});
this.props.fetchRequiredData().then(() => this.setState({pending: false}));
}
componentWillUpdate(nextProps, nextState) {
this.setState({pending: true});
this.props.fetchRequiredData().then(() => this.setState({pending: false}));
}
}
最佳答案
您可以将所有 Promise 映射到一个数组中,然后使用 Promise.all()
函数来解决所有问题:
const allPromises = requiredAccounts.map(account => {
return dispatch(fetchAccount(account)); // Returns a promise
});
Promise.all(allPromises).then(() => {
// ... do something after all promises were resolved ...
});
关于javascript - 从 .map() 方法内的调度函数返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788017/