javascript - 为什么 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
为什么会这样?
解决方案
原始代码是用 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
推荐阅读
- shell - 使用 shell 脚本调用 SNS ansible 脚本
- vba - 交换字符在单元格中的位置
- c# - 无法删除具有要查看的导航属性的实体
- php - 当我的页面在 Wordpress 中加载时如何自动向下滚动?
- bash - 从 bash 脚本运行 groovy 脚本
- reporting-services - SSRS 查询测试用例结果
- phpstorm - PhpStorm 和 Xdebug 不工作
- sql - ORA-29913: 执行 ODCIEXTTABLEOPEN 标注时出错
- angular - 添加插值时的链接问题
- javascript - 在 before() 中使用 .then 时无法期待 chakram 中的状态