• 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

  • 相关阅读:
    C++中的一些困惑(长期更新中)
    【数据聚类】基于粒子群、遗传和差分算法实现数据聚类附matlab代码
    uniapp 微信小程ios端键盘弹起后导致页面无法滚动
    C#更改图的PixelFormat
    复现一次循环和两次循环
    12V铅酸电池充放电保护板
    对开源自动化测试平台MeterSphere的使用感触
    成为测试/开发程序员,小张:现实就来了个下马威......
    Android自动化测试工具调研
    Effective java 总结11 - 序列化
  • 原文地址:https://blog.csdn.net/qq_34569497/article/details/133911252