Home > Enterprise >  Program terminates after await statement in javascript
Program terminates after await statement in javascript

Time:09-19

I am learning async javascript, and I am struck with a doubt here. Here is my simple code:

function delay(sec)
{
    return new Promise(()=>{
        setTimeout(()=>{
            console.log("Inside settimeout");
        },sec);
    })
}

async function print()
{
    await delay(2000);
    console.log("Outside settimeout");
}

print();

In the above program I expected that due to await keyword, the delay function will wait for 2 seconds, output "Inside settimeout" and then output "Outside settimeout". But instead, it just logs "Inside settimeout" and simply terminates without logging "Outside settimeout". Can someone clear my doubt and explain how this works? Thanks in advance.

CodePudding user response:

You are missing the resolve call in your promise.

function delay(sec)
{
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            console.log("Inside settimeout");
            resolve();
        },sec);
    })
}

async function print()
{
    await delay(2000);
    console.log("Outside settimeout");
}

print();

CodePudding user response:

You have a Promise that never resolves since you never call the resolve function. Here would be the fixed function.

function delay(ms = 0) {
  return new Promise((resolve, reject) => setTimeout(resolve ,ms))
}
  • Related