0

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?

0

2 Answers 2

1

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 other answer would probably make more sense.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.