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


    难点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
  • 相关阅读:
    【Linux operation 38】解决Linux 端口被占用
    2023国家工业软件大会:科东软件与您共创智能时代,引领产业变革!
    第十三章《集合》第5节:Map集合
    nodejs+vue+elementui高校体育馆场地预订系统
    java计算机毕业设计微服务在线考试源码+系统+数据库+lw文档
    智能变电站网络报文记录及故障录波分析装置
    Dijkstra求最短路—priority堆优化;
    Centos7 安装 Etcd
    ctf:kali工具ettercap,setoolkit
    自动驾驶 - 滤波算法
  • 原文地址:https://blog.csdn.net/weixin_50948265/article/details/128136793