Skip to content

Why this code snippet when run in Node print the output and exit without waiting but in Deno it prints the output; waits for some time and then exits

async function quick_function(){
    const x = await Promise.all([sleep(1000), sleep(2000)]);
    console.log(x[0]);
    console.log(x[1]);
}


async function sleep(time){
    const x = await new Promise((resolve)=>{
        setTimeout(resolve(time),time);
    });
    return x;
}


async function lazy_function(){
    await sleep(2000);
    await sleep(3000);
    console.log("finally");
}



quick_function();
lazy_function();

Please someone explain why the above code snippet when run in Node.js print the output and exit without waiting but in Deno it waits for some time and then exits.

The output

1000
2000
finally

Answer

Your sleep function is not working as expected. You must wrap the resolve in a lambda to have it works as intended:

async function quick_function(){
    const x = await Promise.all([sleep(1000), sleep(2000)]);
    console.log(x[0]);
    console.log(x[1]);
}


async function sleep(time){
    const x = await new Promise((resolve)=>{
        setTimeout(() => resolve(time), time);
    });
    return x;
}


async function lazy_function(){
    await sleep(2000);
    await sleep(3000);
    console.log("finally");
}

quick_function();
lazy_function();

In this fixed code, both node and deno will behave similarly.

As for why there was a timing difference in the original code between the two runtimes, I feel it must be related on the way deno introduced top-level await capability recently.