Home > Blockchain >  async await not working as expected with react
async await not working as expected with react

Time:08-30

I am calling an async function inside useEffect hook in react as below.

const ab = async () => {
    console.log("start API");
    await callAPI();
    console.log("end API");
};

useEffect(() => {
    ab();
    console.log("calling");
}, []);

As the output first it will print start API then print calling and finally print end API. But what I need as the printing order is start API, end API, and calling. That's why I am using async await as well. But it's not working as expected. Any way to fix this issue?

CodePudding user response:

That's the point of using await – the execution is paused until callAPI is finished.

To achieve the order you want, don't use await and just let the code run asynchronously. This way, the synchronous code (console.log('calling')) will be ran without waiting for the asynchronous code (callAPI()) to finish.

EDIT: However, depending on your use case, the solution provided by Giorgi Moniava would probably make more sense.

CodePudding user response:

You must await ab also, but that requires you to make outer function which you pass to useEffect also async, but useEffect may complain if you pass it async function, hence the wrapper:

import React from 'react';
import './style.css';
let test = () => new Promise((resolve) => setTimeout(() => resolve(1)));
let ab = async () => {
  console.log('START');
  await test();
  console.log('END');
};
export default function App() {
  React.useEffect(() => {
    let wrapper = async () => {
      await ab(); // --> must await here too
      console.log('Hi');
    };
    wrapper();
  }, []);
  return (
    <div>test</div>
  );
}

CodePudding user response:

For async/await to work , you'll have to await an asynchronous function. Hence use the following code.

  useEffect(() => {
    let helper = async () => {
      await ab(); // write await here
      console.log('calling');
    };
    helper();
  }, []);

Now the output would be:

Start API
End API
calling
  • Related