• 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

  • 相关阅读:
    附近商户-实现附近商户功能
    BUUCTF [BJDCTF2020]认真你就输了 1
    JVM系列一
    代码随想录算法训练营第五十三天| LeetCode1143. 最长公共子序列、LeetCode1035. 不相交的线、LeetCode53. 最大子数组和
    如何在CentOS部署JumpServer堡垒机并实现无公网ip环境远程访问
    k8s系列(二)之k8s高可用集群环境搭建
    Rust升级慢,使用国内镜像进行加速
    Prompts(二)
    【linux命令讲解大全】057.UNIX实用命令详解:col、colrm和dircolors的用法
    30天工作量,推荐4个ai写作生成器工具,一键搞定!
  • 原文地址:https://blog.csdn.net/qq_34569497/article/details/133911252