学习自:https://www.bilibili.com/video/BV1GA411x7z1

1 概念

1.1 定义

  1. 抽象表达:
  • Promise 是一门新的技术(ES6 规范)
  • Promise 是 JS 中进行异步编程的新解决方案,旧方案是单纯使用回调函数
  1. 具体表达:
  • 从语法上来说: Promise 是一个构造函数
  • 从功能上来说: Promise 对象用来封装一个异步操作并可以获取其成功/失败的结果值

    1.2. 状态改变

    一个 Promise 必然处于以下几种状态之一:

  • 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。

  • 已兑现(fulfilled): 意味着操作成功完成。
  • 已拒绝(rejected): 意味着操作失败。

说明: 只有这 2 种, 且一个 promise 对象只能改变一次。无论变为成功还是失败, 都会有一个结果数据。成功的结果数据一般称为 value, 失败的结果数据一般称为 reason

  1. let promise = new Promise((resolve, reject) => {
  2. // do something
  3. if (xxx) {
  4. // 将参数返回,供then方法使用
  5. resolve("value");
  6. } else {
  7. // 将参数返回,供then方法使用
  8. reject("error");
  9. }
  10. });
  • pending 变为 resolved
  • pending 变为 rejected

1.3 Promise基本流程

image.png

1.4 使用举例

  1. // 1) 创建 promise 对象(pending 状态), 指定执行器函数
  2. const p = new Promise((resolve, reject) => {
  3. // 2) 在执行器函数中启动异步任务
  4. setTimeout(() => {
  5. const time = Date.now();
  6. // 3) 根据结果做不同处理
  7. // 3.1) 如果成功了, 调用 resolve(), 指定成功的 value, 变为 resolved 状 态
  8. if (time % 2 === 1) {
  9. resolve("成功的值:" + time);
  10. } else {
  11. // 3.2) 如果失败了, 调用 reject(), 指定失败的 reason, 变为rejected 状态
  12. reject("失败的值:" + time);
  13. }
  14. }, 2000);
  15. });
  16. // 4) 能 promise 指定成功或失败的回调函数来获取成功的 vlaue 或失败的 reason
  17. p.then(
  18. (value) => {
  19. // 成功的回调函数 onResolved, 得到成功的 vlaue
  20. console.log("成功! ", value);
  21. },
  22. (reason) => {
  23. // 失败的回调函数 onRejected, 得到失败的 reason
  24. console.log("失败! ", reason);
  25. }
  26. );

1.5 解决回调地狱

回调函数

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.

  1. function sayhello (name, callback) {
  2. console.log(name);
  3. callback();
  4. };
  1. //回调地狱
  2. sayhello("first", function () {
  3. sayhello("second", function () {
  4. sayhello("third", function () {
  5. console.log("end");
  6. });
  7. });
  8. });

Promisefy

  1. const promisefy = fn => {
  2. return function(...args) {
  3. return new Promise((resolve, reject) => {
  4. args.push((err, result) => {
  5. if (err) {
  6. reject(err);
  7. }
  8. resolve(result);
  9. });
  10. fn.apply(this, args);
  11. });
  12. };
  13. };

2 API

2.1 构造函数

Promise 构造函数: Promise (excutor) {}

  • executor 函数: 执行器 (resolve, reject) => {}
    • resolve 函数: 内部定义成功时我们调用的函数 value => {}
    • reject 函数: 内部定义失败时我们调用的函数 reason => {}

说明: executor 会在 Promise 内部立即同步调用,异步操作在执行器中执行

  1. let promise = new Promise(function(resolve) {
  2. console.log("Promise");
  3. resolve();
  4. console.log("!!!")
  5. });
  6. promise.then(function() {
  7. console.log("resolved.");
  8. });
  9. console.log("Hi!");
  10. // Promise
  11. // !!!
  12. // Hi!
  13. // resolved

2.2 then

Promise.prototype.then 方法:(onResolved, onRejected) => {}

  • onResolved 函数: 成功的回调函数 (value) => {}
  • onRejected 函数: 失败的回调函数 (reason) => {}

说明: 指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调。返回一个新的 promise 对象,

2.3 catch

Promise.prototype.catch方法: (onRejected) => {}

  • onRejected函数: 失败的回调函数 (reason) => {}

说明: then()的语法糖, 相当于: then(undefined, onRejected)也返回一个新的 promise 对象

  1. let p = new Promise((resolve, reject) => {
  2. //修改 promise 对象的状态
  3. reject('error');
  4. });
  5. //执行 catch 方法
  6. p.catch(reason => {
  7. console.log(reason);
  8. });


2.4 resolve

Promise.resolve 方法:(value) => { }

  • value: 成功的数据 或 promise 对象

说明: 返回一个成功/失败的 promise 对象

  • 如果传入的参数为非 Promise 类型的对象, 则返回的结果为成功 promise 对象
  • 如果传入的参数为 Promise 对象, 则参数的结果决定了 resolve 的结果

    1. let p2 = Promise.resolve(new Promise((resolve, reject) => {
    2. resolve('OK');
    3. // reject('Error');
    4. }));
    5. console.log(p2);//Promise { 'OK' }
    6. p2.then(res=>console.log(res)) //OK

    2.5 reject

    Promise.reject 方法:(reason) => { }

  • reason: 失败的原因

说明: 返回一个失败的 promise 对象

  1. let p2 = Promise.resolve(new Promise((resolve, reject) => {
  2. // resolve('OK');
  3. reject('Error');
  4. }));
  5. console.log(p2);//Promise { <rejected> 'Error' }
  6. p2.catch(res=>console.log(res)) //Error

2.6 all

Promise.all方法: (promises) => { }

  • promises: 包含 n 个 promise 的数组

说明: 返回一个新的 promise, 只有所有的 promise 都成功才成功, 只要有一个失败了就直接失败。

  1. let p1 = new Promise((resolve, reject) => {
  2. resolve('OK');
  3. })
  4. let p2 = Promise.resolve('Success');
  5. let p3 = Promise.resolve('Oh Yeah');
  6. const result = Promise.all([p1, p2, p3]);

image.png

2.7 race

Promise.race方法:(promises) => {}

  • promises: 包含 n 个 promise 的数组

说明: 返回一个新的 promise,race 就是竞速的意思,最快返回的 promise 的结果状态就是最终的结果状态。

https://mp.weixin.qq.com/s/zRodAnxknMgwj0MUBbW_LQ