0

I am trying to make a wait function that takes a time and waits for that time, but it is not working as I expect it to.

var wait = async (t)=>{
    var c = new Promise((resolve,reject)=>{setTimeout(()=>{resolve()},t)})
    await c
    console.log(2)
}
console.log(1)
wait(100)
console.log(3)

I know I can wait with plain setTimeout(), but I do not want to use that.

James Whiteley
  • 3,363
  • 1
  • 19
  • 46
Mert Çelik
  • 334
  • 1
  • 10
  • Does this answer your question: https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – igg Jan 15 '20 at 09:25
  • `async` return promises. Unless everything inside them is synchronous (which `setTimeout` is not) they don't block. `await` can give the illusion of a promise being synchronous, which you should know since you are using it already, you're just not being it before `wait(100)`. – Quentin Jan 15 '20 at 09:26
  • no its not because of that waits it inside `async` function – Mert Çelik Jan 15 '20 at 09:27
  • @MertÇelik — And while the function is waiting for the promise to resolve it goes to sleep and *the rest of the code runs*. (The rest of the code is not awaiting the promise) – Quentin Jan 15 '20 at 09:36
  • @Quentin ok i understand why its not working but i didn't understand `what to do` – Mert Çelik Jan 15 '20 at 10:15
  • Like I said: `await wait(100)` – Quentin Jan 15 '20 at 10:16
  • i know i can make it with doing it inside async function but how they making functions like `fs.readFileSync()` – Mert Çelik Jan 15 '20 at 10:19
  • just writing full script inside a anonymous async function solves the problem `(async()=>{})()` – Mert Çelik May 03 '20 at 16:29

0 Answers0