ES6 promise 相关方法

94 阅读1分钟
  1. promise 是 es6 引入的异步编程的新解决方案,语法上 promise 是一个构造函数,用来封装异步操作并可以获取成功或失败的结果。

    1. promise 构造函数:promise(excutor){}
    2. promise.prototype.then 方法
    3. promise.protopyte.catch 方法
  2. promise 读取文件

    // 引入 fs模块
    const fs = require("fs");
    
    // 调用方法读取文件
    // fs.readFile("./ES6.md", (err, data) => {
    //     // 如果失败则抛出错误
    //     if (err) throw err;
    //     // 若没有出错,则输出内容
    //     console.log(data.toString());
    // });
    
    // 使用promise封装
    const p = new Promise(function (resolve, reject) {
        fs.readFile("./ES6.md", (err, data) => {
            if (err) reject(err);
            // 如果成功
            resolve(data);
        });
    });
    
    p.then(
        function (value) {
            console.log(value.toString());
        },
        function (reason) {
            console.log("读取失败");
        }
    );
    

3.promise 封装 Ajax 封装

 <script>
            const p = new Promise((resolve, reject) => {
                // 创建对象
                const xhr = new XMLHttpRequest();

                // 初始化
                xhr.open("GET", "https://api.apiopen.top/getJoke");

                // 发送
                xhr.send();

                // 绑定事件,处理响应
                xhr.onreadystatechange = function () {
                    // 判断
                    if (xhr.readyState === 4) {
                        // 判断响应状态码
                        if (xhr.status >= 200 && xhr.status < 300) {
                            resolve(xhr.response);
                        } else {
                            reject(xhr.status);
                        }
                    }
                };
            });

            // 指定失败或成功回调
            p.then(
                function (value) {
                    console.log(value);
                },
                function (reason) {
                    console.error(reason);
                }
            );
        </script>