Javascript 从.map()方法内部的分派函数返回承诺
我正在使用Javascript 从.map()方法内部的分派函数返回承诺,javascript,promise,redux,redux-thunk,Javascript,Promise,Redux,Redux Thunk,我正在使用redux-thunk来处理一些副作用。问题如下。在react组件的某个地方,我有一个函数,负责在组件挂载或获取新道具后获取所有必要的数据,即fetchRequiredData() 在fetchRequiredData()中,我在一个数组上循环,因为每个键都需要获取一些数据。我需要能够有一个过度的承诺,只有当.map()中的承诺得到解决时,它才会得到解决。如果我没有这个,页面就会遇到麻烦,因为它试图呈现它无法呈现的内容 简化代码示例 export const fetchRequired
redux-thunk
来处理一些副作用。问题如下。在react组件的某个地方,我有一个函数,负责在组件挂载或获取新道具后获取所有必要的数据,即fetchRequiredData()
在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}));
}
}
您可以将所有承诺映射到一个数组中,然后使用函数解析所有承诺:
const allPromises = requiredAccounts.map(account => {
return dispatch(fetchAccount(account)); // Returns a promise
});
Promise.all(allPromises).then(() => {
// ... do something after all promises were resolved ...
});
您可以将所有承诺映射到数组中,然后使用函数来解决所有承诺:
const allPromises = requiredAccounts.map(account => {
return dispatch(fetchAccount(account)); // Returns a promise
});
Promise.all(allPromises).then(() => {
// ... do something after all promises were resolved ...
});