zoukankan      html  css  js  c++  java
  • promise系列async,await(二)

    1.async

    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>async</title>
    </head>
    
    <body>
    
        <script>
            async function main() {  //相当于类方法,then()里头的回调函数
                //1. 返回非 promise 的值
                // return 'I miss you';
                //2. 返回是 promise 对象
                // return new Promise((resolve,reject)=>{
                //     // resolve("OK");
                //     reject("error");
                // });
                //3. 抛出错误
                // throw "出错啦!!";
            }
    
            let result = main();
    
            console.log(result);
    
            /**
             *
             * 返回的结果是一个 Promise 对象
             * Promise 对象状态时由返回值 决定的.
              1. 返回非promise的情况
              return '数据';
              2. throw 抛出错误
              throw '失败了!!';
              throw new Error('失败啦!!');
              3. 返回的是一个 Promise 的情况
             */
    
        </script>
    
    </body>
    
    </html>

    2.await

    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>await</title>
    </head>
    
    <body>
        <script>
            //await 必须要放在 async 函数中
            async function main() {
                //声明promise对象
                let p = new Promise((resolve, reject) => {
                    setTimeout(() => {
                        // resolve("成功的值");
                        reject("失败的值");
                    }, 2000)
                });
                //await 右侧一般是promise对象
                // let result = await p;
                console.log(result)
                //await 右侧k可以是其他类型
                // let result = await "abc";
                //promise对象失败了
                try {
                    let result = await p;
                } catch (e) {
                    console.error(e);
                }
            }
    
            main();
        </script>
    </body>
    
    </html>

    3.async和await结合

    //读取 1.html 和 2.html 3.html两个文件内容, 然后合并后输出到控制台
    const fs = require('fs');
    const util = require("util");
    //获取一个返回 promise 对象的函数(读取文件)
    const readFile = util.promisify(fs.readFile);
    
    // readFile(__dirname+ '/resource/1.html').then(value=>{
    //     console.log(value.toString());
    // });
    
    async function main(){
        //读取第一个文件的内容
        let one = await readFile(__dirname+ '/resource/1.html');
        let two = await readFile(__dirname + '/resource/2.html');
        let three = await readFile(__dirname + '/resource/3.html');
        console.log(one.toString() + two.toString() + three.toString());
    }
    main();

    4.async和awiat方式发生ajax请求

    <!doctype html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>async和await处理AJAX</title>
    </head>
    
    <body>
        <script>
            // f发送 ajax 的函数, 返回的结果是 promise 对象
            function promiseAJAX({ url, data, method = "GET" }) {
                return new Promise((resolve, reject) => {
                    //手动调用 resolve 函数
                    let x = new XMLHttpRequest();
                    //初始化
                    x.open(method, url);
                    //发送
                    x.send();
                    //绑定事件, 处理响应结果
                    x.onreadystatechange = function () {// 1->2 2->3  3-> 4
                        //只有状态为 4 的时候, 才能对 Promise 对象状态进行设置
                        if (x.readyState === 4) {
                            //请求成功 2xx 都标识成功   3 重定向   4 客户端错误  5 服务端错误
                            if (x.status >= 200 && x.status < 300) {
                                //成功的话, 将promise对象的状态设置为成功, 并将响应体设置为 promise 对象成功的值
                                resolve(x.response);
                            } else {
                                //失败的话
                                reject(x.status);
                            }
                        }
    
                    }
                });
            }
    
            let url = "https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P";
    
            async function main() {
                //得到 ajax 请求返回的响应体
                let data = await promiseAJAX({url: url});
                console.log(data);
            }
            main();
        </script>
    </body>
    
    </html>
  • 相关阅读:
    小三学算术
    The Balance
    扫描线
    2019牛客暑期多校训练营(第九场)
    后缀数组
    Manacher
    局部变量和全局变量的区别
    2386:Lake Counting-poj
    简单背包问题(0032)-swust oj
    编程中易犯错误集锦-持续更新。。。。。
  • 原文地址:https://www.cnblogs.com/fsg6/p/14549798.html
Copyright © 2011-2022 走看看