简体   繁体   English

为什么 then 回调中的这个循环比异步 function 中的循环更快?

[英]Why is this loop in a then callback faster than in an async function?

While I was playing with TS for learning purposes, I discovered that a then callback takes less than an async function with await.当我出于学习目的而使用 TS 时,我发现 then 回调所需的时间少于带有 await 的异步 function。 Here are my code snippets:这是我的代码片段:

Code with async/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")

result:结果:

notAsync
mainStack
async: 2.464s
billion loops done with async

Code with nested promise:带有嵌套 promise 的代码:

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

result:结果:

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

Why is this happening?为什么会这样?

The original code was written in TypeScript but it was edited and overwritten after posting the question by a community member in JS to be able to run the snippets.原始代码是用 TypeScript 编写的,但在社区成员在 JS 中发布问题后,它被编辑和覆盖,以便能够运行代码片段。

It turned out that the behavior was caused by my TS configuration.事实证明,该行为是由我的 TS 配置引起的。 I had compiler option "target" set to es5 .我将编译器选项“target”设置为es5 After changing its value to es6 I managed to obtain the same results for both snippets.将其值更改为es6后,我设法为两个片段获得了相同的结果。

Original code and results:原始代码和结果:

Code with async/await:带有异步/等待的代码:

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

result:结果:

notAsync
mainStack
async: 2.464s
billion loops done with async

Code with nested promise:带有嵌套 promise 的代码:

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

result:结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM