Home > Software design >  Is await require in sleep function
Is await require in sleep function

Time:01-01

Interesting that without await function the typescript is not complaint and the function is work.

First, Wondering that, do we really need async await in our function?

And, I wanna to avoid the boilerplate of return :Promise<void> for every fn which with async, any clue we can void that?

const App = () => {
  const [ isOpen, setIsOpen ] = useState(false);


  const sleep = (ms: number): Promise<void> => {
     return new Promise((resolve) => setTimeout(resolve, ms));
  }

 // not delay and print "didn't stop", "end", but setIsOpen fn will be delay 2 second
 const withoutAsyncAwait = () => {
   console.log("didn't stop");
   sleep(2000);
   setIsOpen(true); // ---> this will be trigger after 2000
   console.log("end")
 }

 // print "stop await 2second", and stop 2 second 
 const withAsyncAwait = async (): Promise<void> => {
   console.log("stop await 2second");
   await sleep(2000)
   setIsOpen(true);
   console.log("start await");
 }

 return (
  <>
    <div onClick={withAsyncAwait}>
     A Test Button with Await
    </div>
    <div onClick={withoutAsyncAwait}>
      A Test Button without Async await
    </div>
  </>
 )

}

CodePudding user response:

First, Wondering that, do we really need async await in our function?

If you mean, do you need await on sleep(2000) to suspend function execution for two seconds before continuing, then yes, you do. Your "this will trigger after 2000" comment in withoutAsyncAwait is incorrect. It will "trigger" immediately after the call to sleep, with no delay.

And, I wanna to avoid the boilerplate of return :Promise<void> for every fn which with async, any clue we can void that?

In the case of withAsyncAwait, literally just leave it off, and TypeScript will infer that from the fact it's async and what you're returning from the function (in that example, nothing, so void). For sleep, you could just leave it off as well, and TypeScript would infer the return value of Promise<unknown>, which is good enough.

CodePudding user response:

Async await, is used to let the compiler know to wait for the "xyz" thing to load, before continuing the next line of code.

Attempting to load anything (for example, fetching some data from a server) without using Async await, will lead us to this Promise { <pending> } instead of the data you requested.

  • Related