-1

Suppose I have a code like this:

console.log(1);
console.log(2);
setTimeout(() => console.log("Callback fired"),2000);
console.log(3);
console.log(4);

What I wanted to have was logging 1 and 2 in console and then waiting for 2 seconds to log "Callback fired" and then carry on.

I did try using promise but that didn't worked either or perhaps I did it wrong

Ali Esmailpor
  • 1,313
  • 2
  • 8
  • 19
  • Does this answer your question? [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – FZs Feb 05 '21 at 08:23

2 Answers2

2

You have to use async code. Here is an example:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
  //here your code is async
  console.log(1);
  console.log(2);
  await sleep(2000); // sleep for 2 secs
  console.log("timeout over");
  console.log(3);
  console.log(4);
})();
blaumeise20
  • 1,787
  • 2
  • 17
0

You can resolve a Promise inside the callback of setTimeout and await on it in your main logic as below.

(async() => {
  console.log(1);
  console.log(2);
  await awaitThenLog("Callback fired", 2000);
  console.log(3);
  console.log(4);
})();

async function awaitThenLog(message, delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(message);
      resolve();
    }, delay);
  });
}
Udith Gunaratna
  • 1,746
  • 1
  • 10
  • 15