'I am finding it hard to understand why the code after await does not execute

async function setTime() {
    await new Promise(resolve => setTimeout(()=>{console.log("my func is fine")}, 5000));
}

async function realFunction() {
    await setTime();
    console.log("second call!");
}

In the above code, when i call realFunction, it logs my func is fine, but it does not log second call. Can someone help me understand what am I doing wrong, and how can I get the statement to be logged?



Solution 1:[1]

Because you never resolver your promise. You always need to resolve or reject it.

Also async / await is pretty much useless for setTime

function setTime(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

async function realFunction() {
    await setTime(5000);
    console.log("second call!");
}

Solution 2:[2]

The prolbem is that you never resolve the Promise so it's pending forever.

Try to change it like this:

async function setTime() {
  await new Promise((resolve) =>
    setTimeout(() => {
      console.log('my func is fine');
      resolve();
    }, 5000)
  );
}

async function realFunction() {
  await setTime();
  console.log('second call!');
}

Solution 3:[3]

You need to resolve the promise, and for that you can call resolve()

So your setTime() function would look like this:

async function setTime() {
    await new Promise(resolve => setTimeout(()=>{
        console.log("my func is fine")
        return resolve();
    }, 5000));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 OschtärEi
Solution 3 JCV