从.map()方法内的调度函数返回承诺
问题描述:
我正在使用redux-thunk
来管理一些副作用。问题是以下。在我反应组件中的某个地方,我有一个函数负责在组件装载或获取新道具(即fetchRequiredData()
)后获取所有必要的数据。从.map()方法内的调度函数返回承诺
在fetchRequiredData()
我正在循环访问一个数组,因为每个键都需要获取一些数据。我需要能够做出一个完整的承诺,只有在.map()
内的承诺得到解决时才能解决。如果我没有这个页面会遇到麻烦,因为它试图渲染它不能做的事情。
简化代码示例
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.all()
功能来解决这些问题全部:
const allPromises = requiredAccounts.map(account => {
return dispatch(fetchAccount(account)); // Returns a promise
});
Promise.all(allPromises).then(() => {
// ... do something after all promises were resolved ...
});