Reactjs promise.all 调用顺序 [英] Reactjs promise.all order of calls

查看:75
本文介绍了Reactjs promise.all 调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 fetchLoansPromise 之前获取 studentDataPromise,因为它取决于 studentDataPromise 返回的数据.

这是我当前的代码:

Promise.all([studentDataPromise, fetchclassesPromise, fetchLoansPromise]).then(() => {切换IsReady();}).catch(错误=> {抛出新的错误(错误);});

这是当前的事件顺序:

  1. toggleIsReady 最初设置为 false,但现在为 true.
  2. fetchLoansPromise - 无法获取它没有获取 studentDataPromise
  3. studentDataPromise- 正确获取它
  4. toggleIsReady - 现在设置为 false
  5. fetchclassesPromise - 正确获取它

有什么建议吗?

解决方案

我就是这样解决的,现在'fetchStudentData'在'fetchLoansPromise'之前解决了.

 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:

  1. toggleIsReady initially set to false, but is now true.
  2. fetchLoansPromise - can’t fetch it doesn’t have the studentDataPromise fetched
  3. studentDataPromise- fetches it correctly
  4. toggleIsReady - Is now set to false
  5. fetchclassesPromise - fetches it correctly

Any suggestions?

解决方案

This is how I solved it, Now 'fetchStudentData' is resolved before 'fetchLoansPromise'.

    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);
        });

Thank you everyone

这篇关于Reactjs promise.all 调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆