tdcoder
tdcoder

Reputation: 21

Program terminates after await statement in javascript

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.

Upvotes: 0

Views: 125

Answers (2)

Danny
Danny

Reputation: 590

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))
}

Upvotes: 0

Igor Janković
Igor Janković

Reputation: 5532

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();

Upvotes: 1

Related Questions