javascript - React/Redux 和 JavaScript Promise.all
问题描述
我在 React 中遇到了 Promise.all 的问题。我正在为我的 axios 请求创建承诺,最后运行 Promise.all 来调度所有数据。
这是我创建 Promises 的方法:
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
.then()
Promise.all 方法中的日志永远不会运行。
解决方案
axios.get
已经返回了一个 Promise,所以你不需要将它包装在 Promise 构造函数中。请注意,如果您确实构造了一个 Promise,为避免它永远无法解析,您至少必须调用resolve
executor。在您的情况下,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;
});
}