Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从.map()方法内部的分派函数返回承诺_Javascript_Promise_Redux_Redux Thunk - Fatal编程技术网

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 ...
});