ES6精讲14-async异步操作

294 阅读1分钟

1.async:

  • async它会返回一个Promise对象
  • asyncGenerator的一个语法糖
  • 如果async函数中有多个await 那么then函数会等待所有的await指令 运行完的结果 才去执行
async function f() {
       // return await 'hello async';
       let s = await 'hello world';
       let data = await s.split('');
       return data;
   }
// 如果async函数中有多个await 那么then函数会等待所有的await指令 运行完的结果 才去执行
f().then(v => {
    console.log(v)
}).catch(e => console.log(e));

2.try和catch结合

async function f2() {
    // throw new Error('出错了');
    try {
        await Promise.resolve('我要发送请求');
    } catch (error) {
	console.log(error);
    }
    return await Promise.resolve('hello');
}
f2().then(v => console.log(v)).catch(e => console.log(e));
  • 比如 你有个填写表单的弹框。不管你提交成功和失败 我都会把这个弹框关闭掉。那么这个关闭掉弹框的操作。一般就会放在try-catch外面执行。

  • 🌵Try-catch里面的层,不会影响外面层函数的执行

3.改写之前和风天气的请求例子:

const getJSON = function (url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onreadystatechange = handler;
        xhr.responseType = 'json';
        xhr.setRequestHeader('Accept', 'application/json');
        // 发送
        xhr.send();

        function handler() {

            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.response);
                } else {
                    reject(new Error(this.statusText));
                }
            }
        }
    })
}
        
async function getNowWeather(url) {
    // 发送ajax 获取实况天气
    let res = await getJSON(url);
    console.log(res);   //{HeWeather6: Array(1)}
    // 获取HeWeather6的数据   获取未来3~7天的天气状况
    let arr = await res.HeWeather6;
    return arr[0].now;
}
getNowWeather(
        'https://free-api.heweather.net/s6/weather/now?location=dalian&key=c56d9631e4b24ccca21a6e096b12c8a4')
    .then(now => {
        console.log(now);  //{cloud: "91", cond_code: "104", cond_txt: "阴", fl: "22", hum: "85", …}
    })