es6-async的用法

2021-06-16  本文已影响0人  lvyweb

作用:使得异步操作更加方便
基本操作:async会返回一个Promise对象,有了这个对象可以使用then,catch进行调用
async的Generatro的一个语法糖

 async function fn(params) {
      let aa =   await 'hello async';//想用await 必须在async函数中
      let data = await aa.split('');
      return data;

    }
    //如果async有多个await,那么then函数会等待所有的await指令,运行完的结果,才去执行
   fn().then(v=>{console.log(v)}).catch(e=>console.log(e))
  //["h", "e", "l", "l", "o", " ", "a", "s", "y", "n", "c"]

//----------------------------------------------------------------------------------------------------
async function f2(){
      throw new Error('出错了');
}
f2().then(v=>console.log(v)).catch(e=>console.log(e));//Error: 出错了
//----------------------------------------------------------------------------------------------------
await 出错之后不会执行后面的函数 想要执行后面的函数 要这样做
  async function f2(){
    try{
        await Promise.reject('出错了')
    }catch(Error){

    }
    return await Promise.resolve('hello')
}
f2().then(v=>console.log(v)).catch(e=>console.log(e));//hello

需求:获取一个天气

     const getJSON = function(url){
            return new Promise((resolved,rejected)=>{
                    const xhr = new XMLHttpRequest();
                    xhr.open('Get',url);
                    xhr.onreadystatechange = handler;
                    xhr.responseType = 'json';
                    xhr.setRequestHeader('Accept','application/json');
                    //发送
                    xhr.send();
                    function handler(){
                        console.log(this);
                        if(this.readyState === 4){
                            if(this.status == 200){
                                resolved(this.response);
                            }else{
                                rejected(new Error(this.statusText))
                            }
                        }
                    }
            })
        }
        async function getNowWeather(url){
            // 发送ajax 获取天气信息
           let res = await getJSON(url);
        //    let arr = await res.weather 根据上一个结果做另外一个请求,返回两个结果
           console.log(res);
           return res.data;
        }
getNowWeather('https://www.qweather.com/v2/current/condition/s/shanghai-101020100.html?lang=&_=1623856500')
        .then(now=>{
            console.log(now)
        })

总结Generator Promise async

  1. 解决回调地域的问题
  2. 使得异步操作显得更加方便
上一篇下一篇

猜你喜欢

热点阅读