async、await 与 Promise 自己的理解

本文介绍了async函数的特点及其如何与Promise对象交互。通过示例代码详细解释了async函数如何返回Promise对象,以及如何使用await关键字来简化Promise的链式调用。

async函数修饰符

被async修饰的函数特点:

  • 返回一个Promise对象,可以使用then(data=>{})添加回调函数
  • 还可以作为普通函数运行,但函数里面可以使用 await 关键字

async函数返回的是Promise对象

async function f1(){
 return 1
}
async function f2(){
 return Promise.resolve(2)
}
const result1 = f1()
const result2 = f2()
console.log(result1);
console.log(result2);
//f1虽然返回的是1,系统会自动给我们封装成一个promise对象给我们返回

await相当于promise.then成功的情况

// 也就是说,promise.resolve() 就相当于 await

async function fn(){
  const p = Promise.resolve('成功')
  p.then(data=>{
    console.log('data_then',data);
  })
  let await_Data = await p 
  console.log('await_Data',await_Data);
}
fn()
//data_then 成功
// await_Data 成功

//可以可看出,p.then 可以用 await p 替代,
// 结合(一、await自动封装Promise), await 4 其实等于 await Promise.resolve(4)

Promise.catch 异常的情况,对应try…catch

async function fn(){
  const p = Promise.reject('失败')

  // then写法
  p.then((res,rej)=>{
    console.log('data_then',res,rej);
  }).catch(e=>console.log(e))
  // await 写法
  try{
    let await_Data = await p 
    console.log('await_Data',await_Data);
  }catch(e){
    console.log('error',e);
  }
}
fn()
//error 失败
//失败
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值