0

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.

2

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I got it...But why did it terminate without logging "Outside settimeout"
@tdcoder Because the "await" waits for the Promise to resolve, if it doesn't resolve it will wait forever.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.