async与普通函数区别,以及搭配await使用

203 阅读1分钟

async函数 与 普通函数的区别

async 函数 可以使用then catch 方法,普通函数不行

  • 使用then 方式
async function foo(){
  console.log('函数中执行的代码')

  return '888'
}

console.log('函数外执行的代码--start')

// res 为函数return 出来的返回值,若是没有return 则 res为undefined
foo().then(res=>{
  console.log('res:',res)
})

console.log('函数外执行的代码--end')

// 也可以在函数中写then 方法
async function foo(){
  console.log('函数中执行的代码')

  return {
    then:(resovlve,reject)=>{
      resovlve(123456)
    }
  }
}

console.log('函数外执行的代码--start')

foo().then(res=>{
  console.log('res:',res)
})

console.log('函数外执行的代码--end')
  • 使用catch方法
async function foo(){
  console.log('函数中执行的代码')

  throw Error('error message')
}

console.log('函数外执行的代码--start')

foo().catch(err=>{
  console.log('err:',err)
})

console.log('函数外执行的代码--end')
  • async 函数中也可以只用promise
async function foo(){
  console.log('函数中执行的代码')

  return new Promise((resolve,reject)=>{
    // resolve('resolve 返回的值')
    reject('reject 返回的值')
  })
}

console.log('函数外执行的代码--start')

foo().catch(err=>{
  console.log('err:',err)
})

console.log('函数外执行的代码--end')

  • await 配合 async 使用
// 函数必须是promise 返回
function bar(){
  return new Promise((resolve,reject)=>{
    resolve({
      code:200,
      msg:'成功了'
    })
  })
}

async function foo(){
  const { code, msg } = await bar()

  console.log('code:',code,'-----msg:',msg)
}

foo()