Home > Mobile >  I am finding it hard to understand why the code after await does not execute
I am finding it hard to understand why the code after await does not execute

Time:05-10

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?

CodePudding user response:

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!");
}

CodePudding user response:

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!');
}

CodePudding user response:

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));
}
  • Related