• async&await函数


    一种更简洁的方式写出基于Promise的异步行为

    async函数的返回值为一个promise,通过then和catch来捕获内部的返回值

    1.特性:

    1. async函数内部会返回一个promise对象,如果看起来不是promise,那么它将会隐式的包装在promise中(如果代码里返回的不是promise对象,会将其包装成promise对象

    1. async function fn () {
    2.   return 'hello world' 
    3. }

     

    2. await能获取到promise状态改变后的值,如果后面不是一个promise,await 会把该值转换为已正常处理的Promise,结果为undefined

    1. async function fn () {
    2.   await 1 
    3. }

     

    3. await后面promise的状态是reject,则await后的代码不会执行,async函数将返回状态为reject的promise

    1. async function fn() {
    2. await cosle.log("sdf");
    3. console.log(111);
    4. }
    5. console.log(fn());

    4. async函数内部如果存在await,await表达式会暂停整个async函数的执行,等当前位置promise状态改变后才能恢复

    2.面试题分析:

    1. async function fn() {
    2. setTimeout(function () {
    3. console.log(1)
    4. }, 0)
    5. Promise.resolve().then(() => console.log(4))
    6. await setTimeout(function () {
    7. console.log(5)
    8. }, 0)
    9. await Promise.resolve().then(() => console.log(6))
    10. Promise.resolve().then(() => console.log(7))
    11. console.log(3)
    12. }
    13. fn()
    14. //4 6 3 7 1 5

        分析:

    1. 宏任务:setTimeout 1setTimeout 5
    2.     微任务: 4 6--》7
    3.     1.setTimeout 1会放在宏任务中
    4.     2.Promise.resolve().then(() => console.log(4))会放在微任务中
    5.     3.await setTimeout(function () {
    6.         console.log(5)
    7.       }, 0)
    8.       await后面跟的不是promise对象,会将其转为promise对象,并返回undefined
    9.       所以这段代码等价于:
    10.       await Promise.resolve(setTimeout(function(){ console.log(5) },0) 此时有个定时器,所以会放入宏任务中
    11.     4. await Promise.resolve().then(() => console.log(6)) 执行后会将then后面放入微任务中,
    12.     ***到此同步代码执行完(因为await会等待结果输出后再执行下面代码,所以下面的都不开始执行,而这个微任务在微任务4后面,所以需要先执行4,即打印4,6
    13.      打印完后,await当前结果输出继续往下,将7设置进微任务
    14.     5.Promise.resolve().then(() => console.log(7))放入微任务中
    15.     6. 打印console.log(3)
    16.     打印完3以后重新执行微任务7,在执行宏任务 1,5
    17.  最后为4,6,3,7,1,5

  • 相关阅读:
    【面经】讲一下线程池的参数和运行原理
    小哥,你写的SQL执行太慢了!
    TL-ER3220G端口映射设置
    美化Matplotlib的3个小技巧
    Java 调用Python+Opencv实现图片定位
    一文看懂分布式存储架构
    AUTOSAR知识点 之 ECUM (三):ECUM的ISOLAR-AB配置及代码解析
    谷粒商城高级篇-全文检索(ElasticSearch)
    简易的慢SQL自定义告警实战经验(支持多数据源)
    python绘图工具matpoltlib的常用操作
  • 原文地址:https://blog.csdn.net/qq_34569497/article/details/133911252