为什么这个代码片段在 N​​ode 中 运行 打印输出并不等待退出但在 Deno 中它打印输出;等待一段时间然后退出

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

请有人解释为什么上面的代码片段在 Node.js 中 运行 打印输出并退出而不等待,但在 Deno 中它等待一段时间然后退出。

输出

1000
2000
finally

您的 sleep 功能未按预期运行。您必须将 resolve 包装在 lambda 中才能使其按预期工作:

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

在此固定代码中,nodedeno 的行为相似。

至于为什么两个运行时的原始代码存在时序差异,我觉得这一定与最近deno引入top-level await能力的方式有关。