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

难点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

在原本的基础上改变了一点输出,这样的输出可能会更好理解一点,如果还是不好理解可以把这几个块分开,比如把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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值