Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

一道关于事件循环的代码题,希望不吝赐教~

题目:

const pA = () => {
  return new Promise(resolve => {
    resolve()
  })
}

const fn1 = async () => {
  fn2()
}
const fn2 = async () => {
  await pA()
  console.log('b')
}
async function fn() {
  await fn1()
  console.log('a')
}
fn() // b a

为什么输出是先b后a?

我是这么理解的【找bug】:
运行fn,检测到await,其后的代码会被添加到微任务队列,称作任务A,
fn的主代码块执行完毕,执行任务A,
执行fn1,执行fn2,发现了微任务pA()...,添加到微任务队列,称作任务B,
fn1的代码块执行完毕,发现没有返回值,便默认返回了Promise.resolve(),继续执行任务A代码块,【输出a】,
任务A执行完毕,执行任务B,【输出b】

但输出结果是先b后a,想了半天也说服不了自己~
希望各位不吝赐教,Thanks?(?ω?)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const pA = () => {
  return new Promise(resolve => {
    resolve()
  })
}

const fn1 = () => {
  fn2()
    return  Promise.resolve()
}
const fn2 = () => {
  pA().then(() => console.log('b'))
  return Promise.resolve()
}
function fn() {
  fn1().then(() => console.log('a'))
}
fn() // b a

async/await不过是promise语法糖,你把await转为promise.then
比如

await fn1()
console.log('a')

=>

fn1().then(() => console.log('a'))

而且这个是层层嵌套的,如果fn1里也有await,那么同样把fn1替换为内部的promise.then。
await一旦用不好和回调地狱是一样的。它具有迷惑性。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...