0

I have a create-react-app (CRA) using Node and React and Express.

When the user logs in, it will initiate React context like this:

initiateContext = async () => { 

    const promises_1 = [
        this.getBreakthrus(), //check done
        this.getBadges(), //check done
        this.getChapter(), //check done
    ]

    const promises_2 = [
        this.getContext(), //check done
        this.getTeam(), //check done
        this.getTeams(), //check done
        this.getTeamData(), //check done
        this.getFacilitators(), //check done
        this.getNextQuestion(), //check done
    ]

    await Promise.all(promises_1)
    await Promise.all(promises_2);
    this.setLobbyView("profile")
}

These functions load all the data for the application, and initiate the lobby view for the user.

The Problem: When the user is using a VPN connection, sometimes the context data doesn't load. However, the lobby view does load, so the user sees the lobby, but all the data is empty.

How can I make this function more flexible, to handle network failures / retries?

Liam
  • 27,717
  • 28
  • 128
  • 190
Izzi
  • 2,184
  • 1
  • 16
  • 26
  • 1
    You might want to look at this https://www.npmjs.com/package/retry. There are multiple off the shelf packages for this kind of thing – Liam Mar 14 '22 at 14:59
  • Why do you fire of two sets of promises and then await them individually. That doesn't really do anything. The promise is instigated as soon as you call it. There is no point what-so-ever to use two `await Promise.all` – Liam Mar 14 '22 at 15:01
  • I need the first 3 APIs to finish, before the latter set start...? I'm just learning promises, so I thought this was sequencing? – Izzi Mar 14 '22 at 15:03
  • You need to put the first await before `const promises_2 = [` then. This might be your actual issue, not the VPN – Liam Mar 14 '22 at 15:05
  • 2
    Don't do `await Promise.all(promises_1); await Promise.all(promises_2);`, that [may lead to unhandled rejections crashing your app](https://stackoverflow.com/q/45285129/1048572). Either `await Promise.all(promises_1.concat(promises_2));` them in one go, or do the `await Promise.all(promises_1);` *before* `const promises_2 = […]`. – Bergi Mar 14 '22 at 15:11

1 Answers1

1

It looks like your actual issue is a race condition. Your code should be:

initiateContext = async () => { 


    await Promise.all([
        this.getBreakthrus(), //check done
        this.getBadges(), //check done
        this.getChapter(), //check done
    ]);

    //this will now run AFTER the above
    await Promise.all([
        this.getContext(), //check done
        this.getTeam(), //check done
        this.getTeams(), //check done
        this.getTeamData(), //check done
        this.getFacilitators(), //check done
        this.getNextQuestion(), //check done
    ]);
    this.setLobbyView("profile");
};

Also, semi-colons matter

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Liam
  • 27,717
  • 28
  • 128
  • 190