本文介绍了Reactjs promise.all 调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 fetchLoansPromise
之前获取 studentDataPromise
,因为它取决于 studentDataPromise
返回的数据.
这是我当前的代码:
Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise]).then(() => {切换IsReady();}).catch(错误=> {抛出新的错误(错误);});
这是当前的事件顺序:
toggleIsReady
最初设置为 false,但现在为 true.fetchLoansPromise
- 无法获取它没有获取studentDataPromise
studentDataPromise
- 正确获取它toggleIsReady
- 现在设置为 falsefetchclassesPromise
- 正确获取它
有什么建议吗?
解决方案
let studentDataPromise = null;让 fetchClassesPromise = null;让 fetchLoansPromise = null;
useEffect(() => {studentDataPromise = fetchStudentData();}, []);useEffect(() => {fetchClassesPromise = fetchClasses();}, []);useEffect(() => {fetchLoansPromise = resolveStudentDataPromise();}, []);
异步函数 resolveStudentDataPromise() {等待 Promise.all([studentDataPromise]);fetchLoans();}Promise.all([studentDataPromise, fetchClassesPromise, fetchLoansPromise]).then(() => {切换IsReady();}).catch(错误=> {抛出新的错误(错误);});
谢谢大家
I'm trying to fetch the studentDataPromise
before fetchLoansPromise
since it depends on the data studentDataPromise
returns.
This is my current code:
Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise])
.then(() => {
toggleIsReady();
})
.catch(error => {
throw new Error(error);
});
This is the current order of events:
toggleIsReady
initially set to false, but is now true.fetchLoansPromise
- can’t fetch it doesn’t have thestudentDataPromise
fetchedstudentDataPromise
- fetches it correctlytoggleIsReady
- Is now set to falsefetchclassesPromise
- fetches it correctly
Any suggestions?
解决方案
let studentDataPromise = null;
let fetchClassesPromise = null;
let fetchLoansPromise = null;
useEffect(() => {
studentDataPromise = fetchStudentData();
}, []);
useEffect(() => {
fetchClassesPromise = fetchClasses();
}, []);
useEffect(() => {
fetchLoansPromise = resolveStudentDataPromise();
}, []);
async function resolveStudentDataPromise() {
await Promise.all([studentDataPromise]);
fetchLoans();
}
Promise.all([studentDataPromise, fetchClassesPromise, fetchLoansPromise])
.then(() => {
toggleIsReady();
})
.catch(error => {
throw new Error(error);
});
这篇关于Reactjs promise.all 调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!