Promise 的理解与使用

一、promise 的理解
  1. promise 是什么,如下所示:
  • Promise 是一门新的技术(ES6 规范)
  • PromiseJS 中进行异步编程的新解决方案
  • 从语法上来说: Promise 是一个构造函数
  • 从功能上来说: promise 对象用来封装一个异步操作并可以获取其成功/
    失败的结果值
  1. promise 的状态改变,如下所示:
  • pending 变为 resolved
  • pending 变为 rejected
  • 只有这 2 种, 且一个 promise 对象只能改变一次
  • 无论变为成功还是失败, 都会有一个结果数据
  • 成功的结果数据一般称为 value, 失败的结果数据一般称为 reason
  1. promise 指定回调函数的方式更加灵活,如下所示:
  • 旧的: 必须在启动异步任务前指定
  • promise: 启动异步任务 => 返回 promie 对象 => 给 promise 对象绑定回调函数(甚至可以在异步任务结束后指定/多个)
  1. promise 支持链式调用, 可以解决回调地狱问题,如下所示:
  • 回调地狱,回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调执行的条件
  • 回调地狱的缺点,不便于阅读,不便于异常处理
  • 解决方案,promise 链式调用
  • 终极解决方案,async/await
二、promise 的使用
  1. promise 的初体验,代码如下所示:
<!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>promise 基本使用</title>
  <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
  <div class="container">
    <h2 class="page-header">promise 使用</h2>
    <button class="btn btn-primary" id="btn">点击抽奖</button>
  </div>
  <script>
    // 生成随机数
    function rand (m, n) {
      return Math.ceil(Math.random() * (n-m+1)) + m-1;
    }

    // 点击按钮,  1s 后显示是否中奖(30%概率中奖)
    //   若中奖弹出    恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券
    //   若未中奖弹出  再接再厉

    // 获取元素对象
    const btn = document.querySelector('#btn');
    // 绑定单击事件
    btn.addEventListener('click', function () {
      // promise 形式出现
      // resolve 解决  函数类型的数据
      // reject  拒绝  函数类型的数据
      const p = new Promise((resole, reject) => {
        setTimeout(() => {
          // 30%  1-100 1 2 30
          // 获取从1 - 100的一个随机数
          let n = rand(1, 100);
          // 判断
          if (n <= 30) {
            // 将 promise 对象的状态设置为成功
            resole(n); 
          } else {
            // 将 promise 对象的状态设置为失败
            reject(n);
          }
        }, 1000);
      });

      console.log(p);

      // 调用 then 方法
      // value 值
      // reason 理由
      p.then((value) => {
        alert('您的中奖数字为' + value);
      }, (reason) => {
        alert('您的号码为' + reason);
      });
    });
  </script>
</body>
</html>
  1. promisefs 模块,代码如下所示:
const fs = require('fs');

// promise 形式
let p = new Promise((resolve, reject) => { 
  fs.readFile('./resource/content.txt', (err, data) => {
    // 如果出错
    if (err) reject(err);
    // 如果成功
    resolve(data);
  });
});

// 调用 then
p.then(value => {
  console.log(value.toString());
}, reason => {
  console.log(reason);
});

  1. promiseajax 封装,代码如下所示:
<!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>promise 封装 ajax</title>
  <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container">
    <h2 class="page-header">promise 封装 ajax</h2>
    <button class="btn btn-primary" id="btn">点击发送 ajax 请求</button>
  </div>
  <script>
    // 获取元素对象
    const btn = document.querySelector('#btn');

    btn.addEventListener('click', function () {
      // 创建 promise
      const p = new Promise((resolve, reject) => {
        // 1. 创建对象
        const xhr = new XMLHttpRequest();
        // 2. 初始化
        xhr.open('GET', 'https://api.apiopen.top/getJoke');
        // 3. 发送
        xhr.send();
        // 4. 处理响应结果
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            // 判断响应状态码
            if (xhr.status >= 200 && xhr.status < 300) {
              // 控制台输出响应体
              resolve(xhr.response);
            } else {
              // 控制台输出响应状态码
              reject(xhr.status);
            }
          }
        }
      });

      // 调用 then 方法
      p.then(value => {
        console.log(value);
      }, reason => {
        console.warn(reason);
      });
    });
  </script>
</body>
</html>
  1. promise 的封装 fs 模块,代码如下所示:
/**
 * 封装一个函数 mineReadFile 读取文件内容
 * 参数:  path  文件路径
 * 返回:  promise 对象
*/

function mineReadFile (path) {
  return new Promise((resolve, reject) => {
    // 读取文件
    require('fs').readFile(path, (err, data) => {
      // 判断
      if (err) reject(err);
      // 成功
      resolve(data);
    });
  });
}


mineReadFile('./resource/content.txt').then(value => {
  // 输出文件内容
  console.log(value.toString());
}, reason => {
  console.log(reason);
});


  1. util.promisify 方法,代码如下所示:
/**
 * util.promisify 方法
*/

// 引入 util 模块
const util = require('util');
// 引入 fs 模块
const fs = require('fs');
// 返回一个新的函数
let mineReadFile = util.promisify(fs.readFile);

mineReadFile('./resource/content.txt').then(value => {
  console.log(value.toString());
});

  1. promise 封装 ajax,代码如下所示:
<!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>promise 封装 ajax</title>
</head>
<body>
  <script>
    /**
     * 封装一个函数 sendAJAX 发送 GET AJAX 请求
     * 参数   URL
     * 返回结果 Promise 对象
    */

    function sendAJAX () {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'json';
        xhr.open('GET', url);
        xhr.send();
        
        // 处理结果
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            // 判断成功
            if (xhr.status >= 200 && xhr.status < 300) {
              // 成功的结果
              resolve(xhr.response);
            } else {
              reject(xhr.status);
            }
          }
        }
      });
    }


    sendAJAX('https://api.apiopen.top/getJok').then(value => {
      console.log(value);
    }, reason => {
      console.warn(reason);
    });

  </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值