async-await用法解析

340 阅读1分钟

async-await同步语法,消灭回调函数

  • 语法糖,不能改变异步的本质
async function xxx() {
  ...
}

(async function(){
  ...
})()

和promise的关系

  • 消灭回调函数
  • 和promise不冲突,相辅相成

how

  • 执行async函数,返回promise对象
async function fn1(){
  // return 100 //会被封装成promise对象,相当于
  return Promise.resolve(100)
}
const res1 = fn1()  //执行async函数,返回promise对象
res1.then(data => {
  console.log('data', data) //data 100
})
  • await相当于promise的then
!(async function() {
  // const p1 = Promise.resolve(300)
  // const data = await p1 //await相当于promise的then
  const data = await 400 //相当于await Promise.resolve(400)
  console.log('data', data) //data 400
})()

//注意
!(async function() {
  const p1 = Promise.reject('err')  //rejected状态
  const data = await p1 //await => then
  console.log(res)  //不会执行
})()

  • try...catch可捕获异常,代替promise的catch
!(async function() {
  const p1 = Promise.reject('err')
  try{
    const res = await p1  //捕获err
    console.log(res)
  } catch(ex) {
    console.error(ex) //try...catch可捕获异常,代替promise的catch
  }
})()

//第一题
async function async1 () {
  console.log('async1 start') //2
  await async2() //undefined
  // await 后面,都可以看做是callback里的内容,都是异步
  // 先存储在call stack中,执行完同步代码之后再执行
  console.log('async1 end') //5
}

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

console.log('script start') //1
async1()
console.log('script end')   //4

// 运行结果
script start
async1 start
async2
script end
// 同步代码执行完
async1 end
//第二题
async function fn() {
  return 100
}
(async function () {
  const a = fn()  //Promise.resolve(100)
  const b = await fn()  //100
})()
//第三题
(async function (){
  console.log('start')  //start
  const a = await 100
  console.log('a', a)   //a 100
  const b = await Promise.resolve(200)
  console.log('b', b)   //b 200
  const c = await Promise.reject(300)   //此后代码都不会执行
  console.log('c', c)   
  console.log('end')
})

//执行结果
start
a 100
b 200