es6中的async和await

async 函数是终极异步解决方案,使得异步操作变得更加方便。

1,async的用法。它作为一个关键字放到函数前面,用于表示函数是一个异步函数, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。 async会返回promise对象。

	 async function fun(){
        return "hello world!";
    }
    console.log(fun())

在这里插入图片描述
说明:async 函数返回的是一个promise 对象,如果要获取到promise 返回值,要用then 方法 ↓ 。

	async function fun(){
        return "hello world!";
    }
    fun().then(re => {
        console.log(re)
    })//hello world!

2,如果函数内部抛出错误, promise 对象有一个catch 方法进行捕获,await意思是"等待", 关键字只能放到async 函数里面。

async function timeout() {
  const promise=new Promise((resolve,reject)=>{
      setTimeout(()=>resolve('hello world'),2000)
  })
//   错误信息
  const error=false;//如果为true咋报错
  if(!error){
      //等resolve执行完了才执行下一步
      const res=await promise;
      return res;
  }else{
      await promise.reject(new Error("报错了"));
  }
}
timeout()
.then(orr=>console.log(orr))//
.catch(err=>console.log(err));//打印错误信息

3,请求数据

async function getUser(){
    const response=await fetch("http://jsonplaceholder.typicode.com/users");//接口地址
    const data=await response.json();
    return data;
}
getUser().then(users=>console.log(users));

说明:调用getUser方法请求接口,成功以后赋值给data然后返回。await请求接口成功以后才会进行下一步。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值