zl程序教程

您现在的位置是:首页 >  其他

当前栏目

ES6 从入门到精通 # 20:async 的用法

2023-03-14 22:58:57 时间

说明

ES6 从入门到精通系列(全23讲)学习笔记。



async

作用:使得异步操作更加方便

async 它会返回一个 promise 对象,它是 generator 的语法糖

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        async function f() {
            
        }
        console.log(f())
    </script>
</body>
</html>

abab1723b3b348229a8c472ee0a13d29.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        async function f() {
            return await "hello kaimo";
        }
        f().then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        })
    </script>
</body>
</html>



34a52988ae9240fea7e4e4c766271e45.png


如果 async 函数中有多个 await 那么then 函数会等待所有的 await 指令运行完才去执行

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        async function f() {
            let k = await "hello kaimo";
            let data = await k.split("");
            return data;
        }
        f().then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        })
    </script>
</body>
</html>


7fbe313ef6624c3ca6b6d2bd6c9f7f50.png


错误的情况:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        async function f() {
            let k = await "hello kaimo";
            let data = await k.split("");
            return data;
        }
        f().then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        })

        async function f2() {
            throw new Error("报错了");
        }
        f2().then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err);
        })
    </script>
</body>
</html>


60653d753ede4aaf9af2de039d4b5dda.png

如果 await 有多个,里面有错误跟成功的,有错误就会停止。

async function f2() {
    // throw new Error("报错了");
    await Promise.reject("报错了");
    await Promise.resolve("hello kaimo2");
}

e81b33eb95f44f4bad1d7b168faa7454.png


上面这种可以采用 try catch 处理

async function f2() {
    // throw new Error("报错了");
    try {
        await Promise.reject("报错了");
    } catch (error) {
        
    }
    return await Promise.resolve("hello kaimo2");
}

f99075dbabb84770bbf4e030eb6e75d8.png



例子


获取广州天气的 datalist 数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const getData = 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() {
                    console.log(this);
                    if(this.readyState === 4) {
                        if(this.status === 200) {
                            resolve(this.response);
                        }else{
                            reject(new Error(this.statusText));
                        }
                    }
                }
            })
        }

        async function getDataList(url) {
            let res = await getData(url);
            console.log(res);
            // 获取 datalist 数据
            return await res.data;
        }

        getDataList("https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=广州")
            .then(res => {
                console.log(res)
            }, err => {
                console.log(err)
            })

    </script>
</body>
</html>



1bec7e373acd43d4b711a6846964d84d.png