async/await 语法糖的简单原理{笔记篇}

157 阅读1分钟

async 内部做的事情

假如有这样一个 async 函数:

async function getData() {
  return 123
}
let result = getData();
console.log(result); // 123

async 在里面做了以下操作:

function getData(){
  return new Promise((reslove)=>{
    reslove(123)
  })
}
let result = getData()
result.then((data)=>{
  console.log(data)
})
console.log(result) // 123

await 做的事情

假如有这样一个 await 语句:

async function getData(){
  await new Promise((reslove)=>{
    setTimeout(() => {
      console.log(1)
      reslove('data')
    }, 1000)
  })
  await new Promise((reslove)=>{
    setTimeout(() => {
      console.log(2)
      reslove('data')
    }, 2000)
  })
  console.log(3)
}
getData() // 1 2 3

await 在内部做以下操作:

function getData(){
  let p1 = new Promise((reslove)=>{
    setTimeout(() => {
      console.log(1)
      reslove('data')
    }, 1000)
  })
  p1.then(()=>{
    let p2 = new Promise((reslove)=>{
      setTimeout(() => {
        console.log(2)
        reslove('data')
      }, 2000)
    })
    p2.then(()=>{
      console.log(3)
    })
  })
}
getData() // 1 2 3