Home > Mobile >  Call multiple async functions using useEffect
Call multiple async functions using useEffect

Time:10-06

I have the following function that makes a call to the api

  useEffect(() => {
    loadMarkets();
  }, []);

  async function loadMarkets() {
    const marketInformation = await frService.getMarketInfo();
    addMarketInfo(marketInformation.response.data);
  }

I want to make a similar call to loadBooks(). If I don't mind which method comes first, would I be able to just call it like below or should I be wrapping this in 1 async function/wrap it in a Promise?

  useEffect(() => {
    loadMarkets();
    loadBooks();
  }, []);

  async function loadMarkets() {
    const marketInformation = await frService.getMarketInfo();
    addMarketInfo(marketInformation.response.data);
  }

  async function loadBooks() {
    ....

CodePudding user response:

    loadMarkets();
    loadBooks();

because these function are prefixed with the async keyword, these are promise. loadBooks will be fired before loadMarkets finishes.

simple answer, yes you can do as you wrote, however I would try to catch the errors with something like

loadMarkets().catch(doSomethingIfThereIsAnError)

where doSomethingIfThereIsAnError would be a function that does som...

CodePudding user response:

It doesn't really matter which comes first since both of them are async. During the initial rendering of your component, useEffect will invoke both async functions. If you need to check which api endpoint gets called first and how much time it takes for the execution, you can open browser dev tools and check the network tab.

  • Related