Reactjs 所有通话顺序
我试图在Reactjs 所有通话顺序,reactjs,promise,Reactjs,Promise,我试图在fetchLoansPromise之前获取studentDataPromise,因为它取决于studentDataPromise返回的数据 这是我当前的代码: Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise]) .then(() => { toggleIsReady(); }) .catch(error =>
fetchLoansPromise
之前获取studentDataPromise
,因为它取决于studentDataPromise
返回的数据
这是我当前的代码:
Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise])
.then(() => {
toggleIsReady();
})
.catch(error => {
throw new Error(error);
});
这是事件的当前顺序:
toggleIsReady
最初设置为false,但现在为true李>
fetchLoansPromise
-无法获取它未获取studentDataPromise
studentDataPromise
-正确获取它toggleIsReady
-现在设置为falsefetchclassesPromise
-正确获取它Promise.all()
当您传递的所有承诺都得到解决时,就会执行。这意味着您不能保证您的studentDataPromise
在fetchLoanPromise
之前得到解决。我建议看一下这里
解决这个问题的简单方法是,一旦承诺得到解决,就使用.then()
。这可能是这样的:
let studentDataPromise = new Promise((resolve, reject) => {
/**
*
*
* **/
reject(/**Something goes here**/)
/**
* Some Code here
*
*/
resolve(/**Something goes here**/)
})
studentDataPromise
.then((/**Whatever you return from resolve()**/) => {
// Here you can call your fetchLoansPromise
fetchLoansPromise
.then(() => {
/*** ***/
})
})
或者更优雅地使用async/await
:
let studentDataPromise = () => {
return new Promise((resolve, reject) => {
/**
*
* **/
resolve()
})
}
let someAsyncFunction = async () => {
try {
let studentData = await studentDataPromise()
// Here you are guaranteed that your promise resolved
// And you can call your other function
}
catch (err) {
}
}
无论哪种方式,您都必须确保您的第一个承诺得到了解决,然后才能执行其他功能Promise.all()
当您希望确保在您的所有承诺(您传递的承诺)得到解决后发生某些事情时,这一点非常好。
希望这有助于在其他承诺之前致电
studentDataPromise
studentDataPromise().then((data) => {
Promise.all([fetchclassesPromise, fetchLoansPromise])
})
你可以这样做
Promise.all([studentDataPromise, fetchclassesPromise])
.then(([studentData, classesData]) => fetchLoans(studentData))
.then(() => toggleIsReady())
.catch(error => {
// handle exception
});
或使用异步等待:
try {
const [studentData, classesData] = await Promise.all([studentDataPromise, fetchclassesPromise]);
const loansData = await fetchLoans(studentData);
toggleIsRead();
} catch (e) {
// handle exception
}
其中fetchLoansPromise
将返回fetchLoansPromise
我就是这样解决的,现在“fetchStudentData”在“FetchLoanPromise”之前就已经解决了
谢谢大家
如果
fetchLoansPromise
需要studentDataPromise
来解决问题,为什么要使用Promise.all
来并行运行它们?如果希望先使用一个,不要使用Promise.all
。
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);
});