• 字节面试遇到的一个超级复杂的输出题,前端人必看系列,搞定之后再也没有输出题可以难倒你


    难点1:遇到Promise.resolve()/Promise.reject()就相当于平时使用时写在{}里面的内容,功能只有传参和改变promise对象的状态,如果在他们内部执行代码,也是同步代码
    难点2:当await遇到普通函数(非promise/setTimeout)的时候,不阻塞的时候也是按顺序执行的同步代码
    难点3:await遇到promise函数的时候,如果resolve,后面的同步代码都会包裹在then(res => { 这里 })进入微队列等待执行

    console.log('0');
    
    setTimeout(() => {
      console.log('1');
    }, 1 * 2000);
    
    Promise.resolve()
    .then(function() {
      console.log('2');
    }).then(function() {
      console.log('3');
    });
    
    
    async function foo() {
      await bar()
      console.log('4')
    }
    foo()
    
    async function errorFunc () {
      try {
        await Promise.reject('5')
      } catch(e) {
        console.log('6')
      }
      console.log('7');
      return Promise.resolve('8')
    }
    errorFunc().then(res => console.log(9))
    
    function bar() {
      console.log('10')
    }
    
    console.log('11');
    // 0 10 11 2 4 6 7 3 9 1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    在原本的基础上改变了一点输出,这样的输出可能会更好理解一点,如果还是不好理解可以把这几个块分开,比如把errorFunc函数先注释一下,分块理解,就会好懂一点

    console.log('0');
    
    setTimeout(() => {
      console.log('1');
    }, 1 * 2000);
    
    Promise.resolve()
    .then(function() {
      console.log('2');
    }).then(function() {
      console.log('3');
    });
    
    async function foo() {
      await Promise.resolve('resolve').then(res => console.log(res))
      await bar()
      console.log('4')
      Promise.resolve('xxx').then(res => console.log(res))
    }
    foo()
    
    async function errorFunc () {
      try {
        await Promise.reject(console.log('5'))
      } catch(e) {
        console.log('6')
      }
      console.log('7');
      return Promise.resolve(console.log('8'))
    }
    errorFunc().then(res => console.log('9'))
    
    function bar() {
      console.log('10')
    }
    
    console.log('11');
    
    // 0 5 11 2 resolve 6 7 8 3 10 4 xxx 9 1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
  • 相关阅读:
    Spring事务的概念(四大特性)
    【FreeRTOS(十三)】任务通知
    项目经理如何做好跨部门沟通?
    初识JVM
    【DL】第 12 章: 生成式深度学习
    基于 Flask-Admin 与 AdminLTE 构建通用后台管理系统
    锐捷交换机系统安装与升级
    数学建模--模型总结(5)
    Windows10用Navicat 定时备份报错80070057
    重温 C# 字典Dictionary类
  • 原文地址:https://blog.csdn.net/weixin_50948265/article/details/128136793