async/await 执行顺序

1.

async function async1 () {
  console.log('async1 start')
  await async2()
  // 因为async1执行时候没有await,那么函数里面如果有await,其后面的代码相当于放在 callback 中,最后执行
  console.log('async1 end')
}

async function async2 () {
  console.log('async2')
}

console.log('script start')
async1()
console.log('script end')

答:

script start
async1 start
async2
script end
async1 end

2.

(async function () {
  console.log('start')
  const a = await 100
  console.log(a)
  const b = await Promise.resolve(200)
  console.log(b)
  const c = await Promise.reject(300)
  // await 捕获不到 rejected状态,这里报错了
  console.log(c)
  console.log('end')
})()

答:

start
100
200

3.

async function async1 () {
  console.log('async1 start')
  await async2()
  console.log('async1 end')
}

async function async2 () {
  console.log('async2')
}

console.log('script start')

setTimeout(() => {
  console.log('setTimeout')
}, 0)

async1()

new Promise((resolve) => {
  console.log('Promise1')
  resolve()
})
  .then(res => {
    console.log('Promise2')
  })

console.log('script end')

答:

script start
async1 start
async2
Promise1
script end
async1 end
Promise2
setTimeout

results matching ""

    No results matching ""