你不知道的 async、await 魔鬼细节

动力锂电池-二阶RC模型等效电路-RLS参数辨识-Simulink 1.锂电池二阶RC等效电路模型 阅读详情

0、前言

关于promise、async/await的使用相信很多小伙伴都比较熟悉了,但是提到事件循环机制输出结果类似的题目,你敢说都会?

图片.png

试一试?

🌰1:

async function async1 () {
    await new Promise((resolve, reject) => {
        resolve()
    })
    console.log('A')
}
​
async1()
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
​
// 最终结果👉: B A C D
复制代码

🌰2:

async function async1 () {
    await async2()
    console.log('A')
}
​
async function async2 () {
    return new Promise((resolve, reject) => {
        resolve()
    })
}
​
async1()
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
​
// 最终结果👉: B C D A
复制代码

❓基本一样的代码为什么会出现差别,话不多说👇

1、async 函数返回值

在讨论 await 之前,先聊一下 async 函数处理返回值的问题,它会像 Promise.prototype.then 一样,会对返回值的类型进行辨识。

👉根据返回值的类型,引起 js引擎 对返回值处理方式的不同

📑结论:async函数在抛出返回值时,会根据返回值类型开启不同数目的微任务

  • return结果值:非thenable、非promise(不等待)
  • return结果值:thenable(等待 1个then的时间)
  • return结果值:promise(等待 2个then的时间)

🌰1:

async function testA () {
    return 1;
}
​
testA().then(() => console.log(1));
Promise.resolve()
    .then(() => console.log(2))
    .then(() => console.log(3));
​
// (不等待)最终结果👉: 1 2 3
复制代码

🌰2:

async function testB () {
    return {
        then (cb) {
            cb();
        }
    };
}
​
testB().then(() => console.log(1));
Promise.resolve()
    .then(() => console.log(2))
    .then(() => console.log(3));
​
// (等待一个then)最终结果👉: 2 1 3
复制代码

🌰3:

async function testC () {
    return new Promise((resolve, reject) => {
        resolve()
    })
}

testC().then(() => console.log(1));
Promise.resolve()
    .then(() => console.log(2))
    .then(() => console.log(3));
    
// (等待两个then)最终结果👉: 2 3 1




async function testC () {
    return new Promise((resolve, reject) => {
        resolve()
    })
} 

testC().then(() => console.log(1));
Promise.resolve()
    .then(() => console.log(2))
    .then(() => console.log(3))
    .then(() => console.log(4))

// (等待两个then)最终结果👉: 2 3 1 4
复制代码

看了这三个🌰是不是对上面的结论有了更深的认识?

稍安勿躁,来试试一个经典面试题👇

async function async1 () {
    console.log('1')
    await async2()
    console.log('AAA')
}
​
async function async2 () {
    console.log('3')
    return new Promise((resolve, reject) => {
        resolve()
        console.log('4')
    })
}
​
console.log('5')
​
setTimeout(() => {
    console.log('6')
}, 0);
​
async1()
​
new Promise((resolve) => {
    console.log('7')
    resolve()
}).then(() => {
    console.log('8')
}).then(() => {
    console.log('9')
}).then(() => {
    console.log('10')
})
console.log('11')
​
// 最终结果👉: 5 1 3 4 7 11 8 9 AAA 10 6
复制代码

👀做错了吧?

哈哈没关系,送一篇关于JS的事件循环机制秘籍文章:JS的事件执行机制

步骤拆分👇:

  1. 先执行同步代码,输出5

  2. 执行setTimeout,是放入宏任务异步队列中

  3. 接着执行async1函数,输出1

  4. 执行async2函数,输出3

  5. Promise构造器中代码属于同步代码,输出4

    async2函数的返回值是Promise,等待2个then后放行,所以AAA暂时无法输出

  6. async1函数暂时结束,继续往下走,输出7

  7. 同步代码,输出11

  8. 执行第一个then,输出8

  9. 执行第二个then,输出9

  10. 终于等到了两个then执行完毕,执行async1函数里面剩下的,输出AAA

  11. 再执行最后一个微任务then,输出10

  12. 执行最后的宏任务setTimeout,输出6

❓是不是豁然开朗,欢迎点赞收藏!

2、await 右值类型区别

2.1、非 thenable

🌰1:

async function test () {
    console.log(1);
    await 1;
    console.log(2);
}
​
test();
console.log(3);
// 最终结果👉: 1 3 2
复制代码

🌰2:

function func () {
    console.log(2);
}
​
async function test () {
    console.log(1);
    await func();
    console.log(3);
}
​
test();
console.log(4);
​
// 最终结果👉: 1 2 4 3
复制代码

🌰3:

async function test () {
    console.log(1);
    await 123
    console.log(2);
}
​
test();
console.log(3);
​
Promise.resolve()
    .then(() => console.log(4))
    .then(() => console.log(5))
    .then(() => console.log(6))
    .then(() => console.log(7));
​
// 最终结果👉: 1 3 2 4 5 6 7
复制代码

Note:

await后面接非 thenable 类型,会立即向微任务队列添加一个微任务then,但不需等待

2.2、thenable类型

async function test () {
    console.log(1);
    await {
        then (cb) {
            cb();
        },
    };
    console.log(2);
}
​
test();
console.log(3);
​
Promise.resolve()
    .then(() => console.log(4))
    .then(() => console.log(5))
    .then(() => console.log(6))
    .then(() => console.log(7));
​
// 最终结果👉: 1 3 4 2 5 6 7
复制代码

Note:

await 后面接 thenable 类型,需要等待一个 then 的时间之后执行

2.3、Promise类型

async function test () {
    console.log(1);
    await new Promise((resolve, reject) => {
        resolve()
    })
    console.log(2);
}
​
test();
console.log(3);
​
Promise.resolve()
    .then(() => console.log(4))
    .then(() => console.log(5))
    .then(() => console.log(6))
    .then(() => console.log(7));
​
// 最终结果👉: 1 3 2 4 5 6 7
复制代码

❓为什么表现的和非 thenable 值一样呢?为什么不等待两个 then 的时间呢?

Note:

  • TC 39(ECMAScript标准制定者) 对await 后面是 promise 的情况如何处理进行了一次修改,移除了额外的两个微任务,在早期版本,依然会等待两个 then 的时间
  • 掘金上有大佬翻译了官方解释:更快的 async 函数和 promises,但在这次更新中并没有修改 thenable 的情况

这样做可以极大的优化 await 等待的速度👇

async function func () {
    console.log(1);
    await 1;
    console.log(2);
    await 2;
    console.log(3);
    await 3;
    console.log(4);
}
​
async function test () {
    console.log(5);
    await func();
    console.log(6);
}
​
test();
console.log(7);
​
Promise.resolve()
    .then(() => console.log(8))
    .then(() => console.log(9))
    .then(() => console.log(10))
    .then(() => console.log(11));
​
// 最终结果👉: 5 1 7 2 8 3 9 4 10 6 11
复制代码

Note:

await 和 Promise.prototype.then 虽然很多时候可以在时间顺序上能等效,但是它们之间有本质的区别。

  • test 函数中的 await 会等待 func 函数中所有的 await 取得 恢复函数执行 的命令并且整个函数执行完毕后才能获得取得 恢复函数执行的命令;
  • 也就是说,func 函数的 await 此时不能在时间的顺序上等效 then,而要等待到 test 函数完全执行完毕;
  • 比如这里的数字6很晚才输出,如果单纯看成then的话,在下一个微任务队列执行时6就应该作为同步代码输出了才对。

所以我们可以合并两个函数的代码👇

async function test () {
    console.log(5);
​
    console.log(1);
    await 1;
    console.log(2);
    await 2;
    console.log(3);
    await 3;
    console.log(4);
    await null;
    
    console.log(6);
}
​
test();
console.log(7);
​
Promise.resolve()
    .then(() => console.log(8))
    .then(() => console.log(9))
    .then(() => console.log(10))
    .then(() => console.log(11));
​
// 最终结果👉: 5 1 7 2 8 3 9 4 10 6 11
复制代码

因为将原本的函数融合,此时的 await 可以等效为 Promise.prototype.then,又完全可以等效如下代码👇

async function test () {
    console.log(5);
    console.log(1);
    Promise.resolve()
        .then(() => console.log(2))
        .then(() => console.log(3))
        .then(() => console.log(4))
        .then(() => console.log(6))
}
​
test();
console.log(7);
​
Promise.resolve()
    .then(() => console.log(8))
    .then(() => console.log(9))
    .then(() => console.log(10))
    .then(() => console.log(11));
​
// 最终结果👉: 5 1 7 2 8 3 9 4 10 6 11
复制代码

以上三种写法在时间的顺序上完全等效,所以你 完全可以将 await 后面的代码可以看做在 then 里面执行的结果,又因为 async 函数会返回 promise 实例,所以还可以等效成👇

async function test () {
    console.log(5);
    console.log(1);
}
​
test()
    .then(() => console.log(2))
    .then(() => console.log(3))
    .then(() => console.log(4))
    .then(() => console.log(6))
​
console.log(7);
​
Promise.resolve()
    .then(() => console.log(8))
    .then(() => console.log(9))
    .then(() => console.log(10))
    .then(() => console.log(11));
​
// 最终结果👉: 5 1 7 2 8 3 9 4 10 6 11
复制代码

可以发现,test 函数全是走的同步代码...

所以👉:async/await 是用同步的方式,执行异步操作

3、🌰

🌰1:

async function async2 () {
    new Promise((resolve, reject) => {
        resolve()
    })
}
​
async function async3 () {
    return new Promise((resolve, reject) => {
        resolve()
    })
}
​
async function async1 () {
    // 方式一:最终结果:B A C D
    // await new Promise((resolve, reject) => {
    //     resolve()
    // })
​
    // 方式二:最终结果:B A C D
    // await async2()
​
    // 方式三:最终结果:B C D A
    await async3()
​
    console.log('A')
}
​
async1()
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
复制代码

大致思路👇:

  • 首先,async函数的整体返回值永远都是Promise,无论值本身是什么
  • 方式一:await的是Promise,无需等待
  • 方式二:await的是async函数,但是该函数的返回值本身是非thenable,无需等待
  • 方式三:await的是async函数,且返回值本身是Promise,需等待两个then时间

🌰2:

function func () {
    console.log(2);
​
    // 方式一:1 2 4  5 3 6 7
    // Promise.resolve()
    //     .then(() => console.log(5))
    //     .then(() => console.log(6))
    //     .then(() => console.log(7))
​
    // 方式二:1 2 4  5 6 7 3
    return Promise.resolve()
        .then(() => console.log(5))
        .then(() => console.log(6))
        .then(() => console.log(7))
}
​
async function test () {
    console.log(1);
    await func();
    console.log(3);
}
​
test();
console.log(4); 
复制代码

步骤拆分👇:

  • 方式一:

    • 同步代码输出1、2,接着将log(5)处的then1加入微任务队列,await拿到确切的func函数返回值undefined,将后续代码放入微任务队列(then2,可以这样理解)
    • 执行同步代码输出4,到此,所有同步代码完毕
    • 执行第一个放入的微任务then1输出5,产生log(6)的微任务then3
    • 执行第二个放入的微任务then2输出3
    • 然后执行微任务then3,输出6,产生log(7)的微任务then4
    • 执行then4,输出7
  • 方式二:

    • 同步代码输出1、2,await拿到func函数返回值,但是并未获得具体的结果(由Promise本身机制决定),暂停执行当前async函数内的代码(跳出、让行)
    • 输出4,到此,所有同步代码完毕
    • await一直等到Promise.resolve().then...执行完成,再放行输出3

方式二没太明白❓

继续👇

function func () {
    console.log(2);
​
    return Promise.resolve()
        .then(() => console.log(5))
        .then(() => console.log(6))
        .then(() => console.log(7))
}
​
async function test () {
    console.log(1);
    await func()
    console.log(3);
}
​
test();
console.log(4);
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
​
// 最终结果👉: 1 2 4    B 5 C 6 D 7 3
复制代码

还是没懂?

继续👇

async function test () {
    console.log(1);
    await Promise.resolve()
        .then(() => console.log(5))
        .then(() => console.log(6))
        .then(() => console.log(7))
    console.log(3);
}
​
test();
console.log(4);
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
​
// 最终结果👉: 1 4    B 5 C 6 D 7 3
复制代码

Note:

综上,await一定要等到右侧的表达式有确切的值才会放行,否则将一直等待(阻塞当前async函数内的后续代码),不服看看这个👇

  • function func () {
        return new Promise((resolve) => {
            console.log('B')
            // resolve() 故意一直保持pending
        })
    }
    ​
    async function test () {
        console.log(1);
        await func()
        console.log(3);
    }
    ​
    test();
    console.log(4);
    // 最终结果👉: 1 B 4 (永远不会打印3)
    ​
    ​
    // ---------------------或者写为👇-------------------
    async function test () {
        console.log(1);
        await new Promise((resolve) => {
            console.log('B')
            // resolve() 故意一直保持pending
        })
        console.log(3);
    }
    ​
    test();
    console.log(4);
    // 最终结果👉: 1 B 4 (永远不会打印3)
    复制代码

🌰3:

async function func () {
    console.log(2);
    return {
        then (cb) {
            cb()
        }
    }
}
​
async function test () {
    console.log(1);
    await func();
    console.log(3);
}
​
test();
console.log(4);
​
new Promise((resolve) => {
    console.log('B')
    resolve()
}).then(() => {
    console.log('C')
}).then(() => {
    console.log('D')
})
​
// 最终结果👉: 1 2 4 B C 3 D
复制代码

步骤拆分👇:

  • 同步代码输出1、2
  • await拿到func函数的具体返回值thenable,将当前async函数内的后续代码放入微任务then1(但是需要等待一个then时间)
  • 同步代码输出4、B,产生log(C)的微任务then2
  • 由于then1滞后一个then时间,直接执行then2输出C,产生log(D)的微任务then3
  • 执行原本滞后一个then时间的微任务then1,输出3
  • 执行最后一个微任务then3输出D

其它🌰:

setTimeout+Promise+Async输出顺序?很简单呀!

4、总结

async函数返回值

  • 📑结论:async函数在抛出返回值时,会根据返回值类型开启不同数目的微任务

    • return结果值:非thenable、非promise(不等待)
    • return结果值:thenable(等待 1个then的时间)
    • return结果值:promise(等待 2个then的时间)

await右值类型区别

  • 接非 thenable 类型,会立即向微任务队列添加一个微任务then,但不需等待

  • 接 thenable 类型,需要等待一个 then 的时间之后执行

  • 接Promise类型(有确定的返回值),会立即向微任务队列添加一个微任务then,但不需等待

    • TC 39 对await 后面是 promise 的情况如何处理进行了一次修改,移除了额外的两个微任务,在早期版本,依然会等待两个 then 的时间

优质文章参考链接:

码字不易,欢迎点赞🚀🚀🚀

来源:https://juejin.cn/post/7194744938276323384
全桥LLC谐振变换器设计与双环控制策略详解 LLC谐振变换器作为高频开关电源的核心拓扑,通过谐振腔实现软开关特性,显著提升转换效率(可达96%以上)。其工作原理基于谐振电感、电容的协同作用,当开关频率接近谐振点时实现ZVS/ZCS。在工业电源、电动汽车充电等场景中,电压电流双环控制策略通过引入电流内环和竞争仲裁机制,有效改善动态响应(实测负载跳变时电压跌落减少60%)。数字控制实现时需注意ADC采样同步和PWM更新时序,而谐振参数测量与温升管理则是工程实践的关键。 阅读详情

相关推荐

RPA 财务共享中心与RPA赋能

在和集团财务官交流的时候,客户经常会提到FSSC,其中有准备建立FSSC,正在建立FSSC,以及已建成FSSC正使用的,当中会有些对FSSC的疑虑和问题,所以花费些时间对FSSC进行了深入调研,从而也有幸拜读了王兴山、陈剑、梅震、钱自严等专业人士写的几本关于FSSC的书,对FSSC的前因后果有了更深入的认识,同时结合自己在FSSC的一些项目经验,故做了本次分享。 本文章主要分享财务共享中心以及R...

weixin_40244959的博客 2757

C# Task中的Func, Action, Async与Await的使用

在说Asnc和Await之前,先说明一下Func和Action委托, Task任务的基础的用法 1. Func Func是一种委托,这是在3.5里面新增的,2.0里面我们使用委托是用Delegate,Func位于System.Core命名空间下,使用委托可以提升效率,例如在反射中使用就可以弥补反射所损失的性能。Action<T>和Func<T,TResult>...

aoyao9093的博客 830

Vanna 2.0:基于LLM的智能文本到SQL框架,实现企业级数据查询与权限控制

文本到SQL技术是自然语言处理与数据库交互的重要桥梁,它允许用户使用日常语言直接查询数据库,无需编写复杂的SQL语句。其核心原理是利用大语言模型理解用户意图,并结合检索增强生成技术,将自然语言问题转换为准确的结构化查询语言。这项技术的价值在于大幅降低了数据访问门槛,提升了业务人员的数据自助分析能力,并能在金融分析、销售报表、运营监控等场景中实现实时数据洞察。Vanna 2.0作为一个开源框架,通过引入用户感知的智能体架构和行级安全策略,解决了企业级应用中的多租户数据隔离与权限控制等关键问题,使得自然语言数据

weixin_42629522的博客 547

建议收藏!async ,await相关知识总结,适用于js基础不错的童鞋

早在很久之前就知道async和awiat的大名了,但我却一直对这个东西也算是不温不火吧; 最近在搞koa的时候 大量出现的 async和await把我搞得有点烦了; 我就单独抽出来 半天时间 好好来解决下整个async和await 可能有的童鞋知道 他是基于es6的promise基础上进行扩展了; 在讲解之前我们就来谈谈 promise的由来的历史吧; 虽然有点废话了 但助你理解async的还是有...

业余前端的职业经历 893

基于Simulink的永磁同步电机(PMSM)无位置传感器矢量控制与龙伯格观测器设计​

本文介绍了基于Simulink的永磁同步电机(PMSM)无位置传感器矢量控制方法,重点讲解了龙伯格观测器的设计与实现。主要内容包括:1)系统架构与数学推导,通过静止坐标系状态方程和极点配置构建观测器;2)Simulink建模步骤,从电机模型搭建到观测器核心代码实现;3)仿真结果对比分析,显示龙伯格观测器相比滑模观测器具有更好的平滑性和抗噪能力;4)工程部署建议,包括参数在线辨识、低速补偿策略和代码生成优化。该方法实现了全速域无感运行,稳态转速误差小于1%,为低成本高可靠性电机控制提供了有效解决方案。

amy_mhd的博客 164

Qt Tab Widget 实战:如何打造一个可动态增删的标签页管理器(附完整代码)

本文深入探讨了使用Qt框架中的Tab Widget控件构建动态标签页管理器的实战方法。通过分析动态增删的核心挑战,提供了完整的C++代码示例,涵盖信号槽机制、页面生命周期管理、上下文菜单实现以及状态持久化等关键功能,帮助开发者打造高效、用户友好的桌面应用界面。

bb456的博客 1047

第十五节:深入理解async和await的作用及各种适用场景和用法

一. 同步VS异步 1. 同步 VS 异步 VS 多线程 同步方法:调用时需要等待返回结果,才可以继续往下执行业务 异步方法:调用时无须等待返回结果,可以继续往下执行业务 开启新线程:在主线程之外开启一个新的线程去执行业务 同步方法和异步方法的本质区别: 调用时是否需要等待返回结果才能继续执行业务 2. 常见的异步方法(都以Async结尾)   ① HttpClient类:Pos...

weixin_34195142的博客 381

手把手排查IOMMU映射故障:从内核日志到硬件寄存器调试全指南

本文详细解析了IOMMU映射故障的排查方法,从内核日志分析到硬件寄存器调试,提供了一套完整的诊断流程。涵盖AMD和Intel平台的特定调试技巧,包括ATS协商失败、DMA传输错误等常见问题的解决方案,并介绍了高级调试工具链的搭建与性能优化策略。

weixin_42666036的博客 361

异步删除async await

异步删除async await

qq_41438838的博客 378

「Debug R」在从名字空间‘XVector’中出口方法时发现了不是S4通用的函数‘parallelSlotNames’...

每当R语言版本更新,Bioconductor的版本随之更替的时候,总会有一些神奇的报错会出现,比如说下面这种。 Error: package or namespace load failed for ‘GenomicRanges’: 在从名字空间‘XVector’中出口方法时发现了不是S4通用的函数‘parallelSlotNames’ 如果读中文读不懂,我们可以把它翻译成英文。 packa...

xuzhougeng blog 2003

【基础演练】Playwright 极简复习:作为 AI-RPA 底座的 Playwright 核心用法

摘要: 2026年,Playwright已从测试工具升级为AI-RPA标准执行底座,周下载量超3300万,被browser-use等AI Agent项目广泛采用。其核心架构通过Playwright Server实现多浏览器协议适配,支持远程连接与高并发隔离(BrowserContext)。自动等待机制显著提升稳定性,但高频交互场景可能需直接使用CDP协议。Playwright凭借跨浏览器兼容性、轻量级隔离和微软官方支持,成为测试、RPA和AI Agent领域的事实标准,未来将主导对话式自动化市场。

ZDQ58818的博客 243

Promise 和async/await 的一些细节联系

Promise 和async/await

weixin_46523071的博客 320

1. SAP Business Application Studio 里创建一个基于 CAP 模型的最简单的 OData 服务

本文基于 SAP Cloud Application Programming 编程模型的 OData 服务开发教程的第一步,简述了 SAP Business Technology Platform 里 Business Application Studio 开发工具的打开方式,创建 Dev Space 以及 CAP 项目的创建步骤,以及如何通过 schema.cds 和 service.cds 分别创建 OData 模型和 OData 服务,最后通过 ports preview 打开 OData 服务预览页

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1803

你不知道的async、await魔鬼细节

取得 恢复函数执行 的命令并且整个函数执行完毕后才能获得取得。类型(有确定的返回值),会立即向微任务队列添加一个微任务。❓基本一样的代码为什么会出现差别,话不多说👇。类型,会立即向微任务队列添加一个微任务。类型,会立即向微任务队列添加一个微任务。函数,但是该函数的返回值本身是**非。一样,会对返回值的类型进行辨识。是用同步的方式,执行异步操作**函数内的后续代码),不服看看这个👇。函数处理返回值的问题,它会像。函数在抛出返回值时,会根据返回值。的情况如何处理进行了一次修改,

<sdffdsfsdfdfs>sfsfsfsdfsdffds</sdfsDS>Fsd 93

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

上一篇: java生成PDF(图片,模板,表格)
下一篇: 抖音二面:“聊聊二维码扫码登录的原理”
码趣资源网
博客等级 码龄4年 269粉丝 518原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值