【问题标题】:React/Redux and JavaScript Promise.allReact/Redux 和 JavaScript Promise.all
【发布时间】:2021-03-14 23:52:48
【问题描述】:

我在 React 中遇到了 Promise.all 的问题。我正在为我的 axios 请求创建 Promise,最后运行 Promise.all 来调度所有数据。

这是我创建 Promise 的方法:

function promiseLoad(nameID, uID, caption) {
    return new Promise( () => {
        axios.get(`${URL}/users/${uID}/name/${nameID}`)
            .then(res => {
                let obj;
                if(res.data !== -1) {
                    obj = {
                        fullName: res.data,
                        caption: caption
                    };
                }
                return obj;
        });
    });
}

然后,在我的导出方法中,我在将 Promise.all 分派给减速器之前运行它。

export const loadUsers = (users, uID) => {
    return dispatch => {
        let promises = [];
        imgs.forEach(element => {
            promises.push(promiseLoad(element.id, uID, element.caption));
        });
            console.log('Promises');
            console.log(promises);
        Promise.all(promises)
            .then(res => {
                console.log('here');
                console.log(res);
                dispatch(getUsers(res));
        });
    }
}

getUsers 只是一个返回类型/动作的辅助方法

export const getUsers = (res) => {
    return {
        type: actionTypes.GET_USERS,
        payload: res
    }
}

当我运行代码时,我可以在日志中看到:

Promises
Array(10) // array with 10 pending promises

Promise.all 的 .then() 方法内的日志,永远不会运行。

【问题讨论】:

    标签: javascript reactjs promise


    【解决方案1】:

    axios.get 已经返回了一个 Promise,因此您不需要将它包装在 Promise 构造函数中。请注意,如果您确实构造了一个 Promise,为了避免它永远无法解析,您至少必须在执行程序中调用 resolve。在您的情况下,promiseLoad 正在返回一个从未解决的 Promise,因此您看不到这些日志。

    function promiseLoad(nameID, uID, caption) {
        return axios.get(`${URL}/users/${uID}/name/${nameID}`)
            .then(res => {
                let obj;
                if(res.data !== -1) {
                    obj = {
                        fullName: res.data,
                        caption: caption
                    };
                }
                return obj;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2020-02-15
      • 2019-05-17
      • 2021-06-23
      相关资源
      最近更新 更多