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


    说明

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    <!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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述

    如果 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>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    在这里插入图片描述

    错误的情况:

    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>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    在这里插入图片描述

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

    async function f2() {
        // throw new Error("报错了");
        await Promise.reject("报错了");
        await Promise.resolve("hello kaimo2");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

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

    async function f2() {
        // throw new Error("报错了");
        try {
            await Promise.reject("报错了");
        } catch (error) {
            
        }
        return await Promise.resolve("hello kaimo2");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    例子

    获取广州天气的 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>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    在这里插入图片描述

  • 相关阅读:
    数字时代,商业智能BI的落地意味着什么
    2024年山东省职业院校技能大赛中职组“网络安全”赛项竞赛试题-B
    国产化之银河麒麟安装.NetCore-包管理器方式
    Nvm,Nrm使用详解
    互联网食堂大比拼,谁才是互联网养猪场?
    本地部署 CogVLM
    计算机毕业设计Java校园统一网络授课平台系统(源码+系统+mysql数据库+Lw文档)
    介绍:C语言—atoi函数
    2款Notepad++平替工具(实用、跨平台的文本编辑器)
    视频编解码 — DCT变换和量化
  • 原文地址:https://blog.csdn.net/kaimo313/article/details/125858242