【发布时间】: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