【问题标题】:Return promise from dispatch function inside .map() method从 .map() 方法中的调度函数返回承诺
【发布时间】:2017-10-02 22:28:15
【问题描述】:

我正在使用redux-thunk 来管理一些副作用。问题如下。在我的 react 组件中的某个地方,我有一个函数负责在组件安装或获取新的 props 时获取所有必要的数据,即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}));
    }
}

【问题讨论】:

    标签: javascript promise redux redux-thunk


    【解决方案1】:

    您可以将所有承诺映射到一个数组中,然后使用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 ...
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2019-04-15
      • 2017-04-05
      • 2016-01-11
      • 2016-06-15
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多