javascript - 从 .map() 方法内的调度函数返回 promise

标签 javascript promise redux redux-thunk

我正在使用 redux-thunk 来管理一些副作用。问题如下。在我的 react 组件中的某个地方,我有一个函数,负责在组件安装或获取新 Prop 后获取所有必要的数据,即 fetchRequiredData()

fetchRequiredData()中,我循环遍历一个数组,因为每个键都需要获取一些数据。我需要能够有一个总体 promise ,只有当 .map() 内的 promise 得到解决时,该 promise 才会得到解决。如果我没有这个,页面就会遇到麻烦,因为它试图渲染它不能渲染的东西。

简化的代码示例

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 映射到一个数组中,然后使用 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 ...
});

关于javascript - 从 .map() 方法内的调度函数返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788017/

相关文章:

reactjs - 如何使用 Redux connect 传递 props

javascript - Angular, packery 指令在页面更改时中断

javascript - Promise.all() 基于返回 Promises 的函数

node.js - Bluebird promisifyAll 与 promisify each 方法

javascript - JavaScript 中 then() 函数的执行

javascript - 使用 Jest 测试化简器文件中的函数

javascript - --如何让这个 React/Redux 代码变得 DRY

javascript - 你能在 React 组件类中添加一个外部函数作为方法吗?

java - 如何从ajax表单中的HttpServletResponse获取数据

javascript - 使用 ng-options 进行错误迭代