Return 从 .map() 方法中的调度函数承诺
Return promise from dispatch function inside .map() method
我正在使用 redux-thunk
来控制一些副作用。问题如下。在我的反应组件中的某个地方,我有一个函数负责在组件安装或获取新道具后获取所有必要的数据,即 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}));
}
}
您可以将所有承诺映射到一个数组中,然后使用 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 ...
});
我正在使用 redux-thunk
来控制一些副作用。问题如下。在我的反应组件中的某个地方,我有一个函数负责在组件安装或获取新道具后获取所有必要的数据,即 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}));
}
}
您可以将所有承诺映射到一个数组中,然后使用 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 ...
});