0

In the code below, I find the console.log("resolve") will be executed two times when I run this code in React. But when I run this code in browser console, there is no problem. Why this happens, I am so confused. Hope you can give me some help, thanks!

export const Wei = () => {

  const myFun = () => {
    let state = false;

    setTimeout(() => {
      state = true;
    }, 2000);

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (state) {
          console.log("resolve");
          resolve("State is true");
        }
        else {
          reject("State is false");
        }
      }, 3000);
    });
  };

  console.log("render");

  const getResult = async () => {
    console.log("before");
    const res = await myFun();
    console.log("after");
    return res;
  };

  console.log(getResult());
  return <div>1</div>;
};
wei wang
  • 135
  • 6
  • how do you run it? – Flash Thunder Aug 25 '21 at 08:27
  • I tried to reproduce it with your code. It works fine. it logs only one time. How do you call the function? – BadPiggie Aug 25 '21 at 08:27
  • I run this code in React, but when I run this code in browser console, there is no problem. – wei wang Aug 25 '21 at 08:30
  • Don't call asynchronous functions from the render function. Use an effect – Bergi Aug 25 '21 at 08:31
  • 1
    You are calling `getResult` and console logging as unintentional side-effects in the function body. This is one of the things React intentionally double invokes if you are running your app in a `StrictMode` component. If this isn't the case then update your question to include a more complete [Minimal, Complete, and Reproducible Code Example](https://stackoverflow.com/help/minimal-reproducible-example). – Drew Reese Aug 25 '21 at 08:31
  • Thank you very much for your reply, because I don't know StrictMode very well now, I may have to study the difference between the two first. My react app is generated using the create-react-app command, and I have not changed the configuration parameters. – wei wang Aug 25 '21 at 08:44

0 Answers0