首页 > 解决方案 > 为什么 then 回调中的这个循环比异步函数中的更快?

问题描述

当我出于学习目的而使用 TS 时,我发现 then 回调比带有 await 的异步函数花费的时间更少。这是我的代码片段:

带有异步/等待的代码:

const asyncCodeBlocker = async function(){
    console.log("notAsync")
    await Promise.resolve();
    console.time("async");
    let i = 0;
    while (i < 1000000000) { i++; }
    console.timeEnd("async");
    return 'billion loops done with async';
}

asyncCodeBlocker().then(v => {console.log(v)})

console.log("mainStack")

结果:

notAsync
mainStack
async: 2.464s
billion loops done with async

带有嵌套承诺的代码:

const promiseCodeBlocker = function(){
    console.log("notAsyncInPromise")
    return Promise.resolve().then(() => {
        console.time("promise");
        let i = 0;
        while (i < 1000000000) { i++; }
        console.timeEnd("promise");
        return 'billion loops done with nested promise';
    })
}

promiseCodeBlocker().then(v => {console.log(v)})

console.log("mainStack")

结果:

notAsyncInPromise
mainStack
promise: 497.627ms
billion loops done with nested promise

为什么会这样?

标签: javascripttypescriptasynchronousasync-awaitpromise

解决方案


原始代码是用 TypeScript 编写的,但在社区成员用 JS 发布问题后,它被编辑和覆盖,以便能够运行代码片段。

事实证明,该行为是由我的 TS 配置引起的。我将编译器选项“target”设置为es5。将其值更改为es6后,我设法为两个片段获得了相同的结果。

原始代码和结果:

带有异步/等待的代码:

const asyncCodeBlocker: () => Promise<any> = async function(){
    console.log("notAsync")
    await Promise.resolve();
    console.time("async");
    let i = 0;
    while (i < 1000000000) { i++; }
    console.timeEnd("async");
    return 'billion loops done with async';
}

asyncCodeBlocker().then(v => {console.log(v)})

console.log("mainStack")

结果:

notAsync
mainStack
async: 2.464s
billion loops done with async

带有嵌套承诺的代码:

const promiseCodeBlocker: () => Promise<any> = function(){
    console.log("notAsyncInPromise")
    return Promise.resolve().then(() => {
        console.time("promise");
        let i = 0;
        while (i < 1000000000) { i++; }
        console.timeEnd("promise");
        return 'billion loops done with nested promise';
    })
}

promiseCodeBlocker().then(v => {console.log(v)})

console.log("mainStack")

结果:

notAsyncInPromise
mainStack
promise: 497.627ms
billion loops done with nested promise

推荐阅读