什么是Promise ?

Promise是JS异步编程中的重要概念,异步抽象处理对象,是目前比较流行Javascript异步编程解决方案之一

Promises/A+ 规范

为实现者提供一个健全的、可互操作的 JavaScript promise 的开放标准。

术语

  • 解决 (fulfill) : 指一个 promise 成功时进行的一系列操作,如状态的改变、回调的执行。虽然规范中用 fulfill 来表示解决,但在后世的 promise 实现多以 resolve 来指代之。
  • 拒绝(reject) : 指一个 promise 失败时进行的一系列操作。
  • 拒因 (reason) : 也就是拒绝原因,指在 promise 被拒绝时传递给拒绝回调的值。
  • 终值(eventual value) : 所谓终值,指的是 promise 被解决时传递给解决回调的值,由于 promise 有一次性的特征,因此当这个值被传递时,标志着 promise 等待态的结束,故称之终值,有时也直接简称为值(value)。
  • Promise : promise 是一个拥有 then 方法的对象或函数,其行为符合本规范。
  • thenable : 是一个定义了 then 方法的对象或函数,文中译作“拥有 then 方法”。
  • 异常(exception) : 是使用 throw 语句抛出的一个值。

    基本要求

    下面我们先来讲述Promise/A+ 规范的几个基本要求。

1. Promise的状态

一个Promise的当前状态必须是以下三种状态中的一种: 等待状态(Pending) 执行状态(Fulfilled) 和 拒绝状态(Rejected)。

  1. const PENDING = 'pending';
  2. const FULFILLED = 'fulfilled';
  3. const REJECTED = 'rejected';
  4. 复制代码

等待状态 (Pending)
处于等待态时,promise 需满足以下条件:

  • 可以迁移至执行态或拒绝态

    1. if (this.state === PENDING) {
    2. this.state = FULFILLED || REJECTED ;
    3. }
    4. 复制代码

    执行状态 (Fulfilled)
    处于执行态时,promise 需满足以下条件:

  • 不能迁移至其他任何状态

  • 必须拥有一个不可变的终值

    1. this.value = value;
    2. 复制代码

    拒绝状态 (Rejected)
    处于拒绝态时,promise 需满足以下条件:

  • 不能迁移至其他任何状态

  • 必须拥有一个不可变的据因

    1. this.reason = reason;
    2. 复制代码

    这里的不可变指的是恒等(即可用 === 判断相等),而不是意味着更深层次的不可变(译者注:盖指当 value 或 reason 不是基本值时,只要求其引用地址相等,但属性值可被更改)

    2. Then 方法

    一个 promise 必须提供一个 then 方法以访问其当前值、终值和据因。
    promise 的 then 方法接受两个参数:

    1. promise.then(onFulfilled, onRejected)
    2. 复制代码

    参数可选
    onFulfilled 和 onRejected 都是可选参数。

  • 如果 onFulfilled 不是函数,其必须被忽略

  • 如果 onRejected 不是函数,其必须被忽略

onFulfilled 特性
如果 onFulfilled 是函数:

  • 当 promise 执行结束后其必须被调用,其第一个参数为 promise 的终值
  • 在 promise 执行结束前其不可被调用
  • 其调用次数不可超过一次

onRejected 特性
如果 onRejected 是函数:

  • 当 promise 被拒绝执行后其必须被调用,其第一个参数为 promise 的据因
  • 在 promise 被拒绝执行前其不可被调用
  • 其调用次数不可超过一次

调用时机
onFulfilled 和 onRejected 只有在执行环境堆栈仅包含平台代码时才可被调用 注1
注1 这里的平台代码指的是引擎、环境以及 promise 的实施代码。实践中要确保 onFulfilled 和 onRejected 方法异步执行,且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。
这个事件队列可以采用“宏任务(macro - task)”机制或者“微任务(micro - task)”机制来实现。
由于 promise 的实施代码本身就是平台代码(译者注:即都是 JavaScript),故代码自身在处理在处理程序时可能已经包含一个任务调度队列。
调用要求
onFulfilled 和 onRejected 必须被作为函数调用(即没有 this 值)
多次调用
then 方法可以被同一个 promise 调用多次

  • 当 promise 成功执行时,所有 onFulfilled 需按照其注册顺序依次回调
  • 当 promise 被拒绝执行时,所有的 onRejected 需按照其注册顺序依次回调

    简易版实践

    我们先通过实践一个简易版的Promise来消化一下上面Promises/A+规范的基本要求。

首先

  1. npm init
  2. // 测试实现是否符合 promises/A+ 规范
  3. npm install promises-aplus-tests -D
  4. 复制代码

package.json

  1. {
  2. "name": "ajpromise",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "promises-aplus-tests ./simple.js"
  8. },
  9. "author": "webfansplz",
  10. "license": "MIT",
  11. "devDependencies": {
  12. "promises-aplus-tests": "^2.1.2"
  13. }
  14. }
  15. 复制代码

simple.js

  1. //Promise 的三种状态 (满足要求 -> Promise的状态)
  2. const PENDING = 'pending';
  3. const FULFILLED = 'fulfilled';
  4. const REJECTED = 'rejected';
  5. class AjPromise {
  6. constructor(fn) {
  7. //当前状态
  8. this.state = PENDING;
  9. //终值
  10. this.value = null;
  11. //拒因
  12. this.reason = null;
  13. //成功态回调队列
  14. this.onFulfilledCallbacks = [];
  15. //拒绝态回调队列
  16. this.onRejectedCallbacks = [];
  17. //成功态回调
  18. const resolve = value => {
  19. // 使用macro-task机制(setTimeout),确保onFulfilled异步执行,且在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。
  20. setTimeout(() => {
  21. if (this.state === PENDING) {
  22. // pending(等待态)迁移至 fulfilled(执行态),保证调用次数不超过一次。
  23. this.state = FULFILLED;
  24. // 终值
  25. this.value = value;
  26. this.onFulfilledCallbacks.map(cb => {
  27. this.value = cb(this.value);
  28. });
  29. }
  30. });
  31. };
  32. //拒绝态回调
  33. const reject = reason => {
  34. // 使用macro-task机制(setTimeout),确保onRejected异步执行,且在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。 (满足要求 -> 调用时机)
  35. setTimeout(() => {
  36. if (this.state === PENDING) {
  37. // pending(等待态)迁移至 fulfilled(拒绝态),保证调用次数不超过一次。
  38. this.state = REJECTED;
  39. //拒因
  40. this.reason = reason;
  41. this.onRejectedCallbacks.map(cb => {
  42. this.reason = cb(this.reason);
  43. });
  44. }
  45. });
  46. };
  47. try {
  48. //执行promise
  49. fn(resolve, reject);
  50. } catch (e) {
  51. reject(e);
  52. }
  53. }
  54. then(onFulfilled, onRejected) {
  55. typeof onFulfilled === 'function' && this.onFulfilledCallbacks.push(onFulfilled);
  56. typeof onRejected === 'function' && this.onRejectedCallbacks.push(onRejected);
  57. // 返回this支持then 方法可以被同一个 promise 调用多次
  58. return this;
  59. }
  60. }
  61. 复制代码

就这样,一个简单的promise就完成了.

  1. new AjPromise((resolve, reject) => {
  2. setTimeout(() => {
  3. resolve(2);
  4. }, 2000);
  5. })
  6. .then(res => {
  7. console.log(res);
  8. return res + 1;
  9. })
  10. .then(res => {
  11. console.log(res);
  12. });
  13. //output
  14. // delay 2s..
  15. // 2
  16. // 3
  17. 复制代码

接下来,我们来看看我们的实现是否完全符合promises/A+规范~

  1. npm run test
  2. 复制代码

GG,测试用例只过了一小部分,大部分飘红~
OK,接下来,我们来继续了解promises/A+ 进一步的规范要求~

进一步要求

由于接下来的要求比较抽象和难理解,所以我们将一步一步实践来加深理解。

1. 返回

  • 1.then方法必须返回一个promise对象
  • 2.如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行下面的 Promise 解决过程:[Resolve]
  • 3.如果 onFulfilled 或者 onRejected 抛出一个异常 e ,则 promise2 必须拒绝执行,并返回拒因 e。
  • 4.如果 onFulfilled 不是函数且 promise1 成功执行, promise2 必须成功执行并返回相同的值。
  • 5.如果 onRejected 不是函数且 promise1 拒绝执行, promise2 必须拒绝执行并返回相同的据因。
  • 6.不论 promise1 被 reject 还是被 resolve 时 promise2 都会被 resolve,只有出现异常时才会被 rejected。

我们通过以上要求来一步一步完善then方法
1.

  1. // 1.首先,then方法必须返回一个promise对象
  2. then(onFulfilled, onRejected) {
  3. let newPromise;
  4. return (newPromise = new AjPromise((resolve, reject) => {}));
  5. }
  6. 复制代码

    1. then(onFulfilled, onRejected) {
    2. let newPromise;
    3. return (newPromise = new AjPromise((resolve, reject) => {
    4. // 2.如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行下面的 Promise 解决过程:[[Resolve]](promise2, x)
    5. this.onFulfilledCallbacks.push(value => {
    6. let x = onFulfilled(value);
    7. //解决过程 resolvePromise
    8. resolvePromise(newPromise, x);
    9. });
    10. this.onRejectedCallbacks.push(reason => {
    11. let x = onRejected(reason);
    12. //解决过程 resolvePromise
    13. resolvePromise(newPromise, x);
    14. });
    15. }));
    16. }
    17. // 解决过程
    18. function resolvePromise() {
    19. //...
    20. }
    21. 复制代码

    1. then(onFulfilled, onRejected) {
    2. let newPromise;
    3. return (newPromise = new AjPromise((resolve, reject) => {
    4. // 3.如果 onFulfilled 或者 onRejected 抛出一个异常 e ,则 promise2 必须拒绝执行,并返回拒因 e。
    5. this.onFulfilledCallbacks.push(value => {
    6. try {
    7. let x = onFulfilled(value);
    8. resolvePromise(newPromise, x);
    9. } catch (e) {
    10. reject(e);
    11. }
    12. });
    13. this.onRejectedCallbacks.push(reason => {
    14. try {
    15. let x = onRejected(reason);
    16. resolvePromise(newPromise, x);
    17. } catch (e) {
    18. reject(e);
    19. }
    20. });
    21. }));
    22. }
    23. 复制代码

    4,5.

    1. then(onFulfilled, onRejected) {
    2. let newPromise;
    3. // 4.如果 onFulfilled 不是函数且 promise1 成功执行, promise2 必须成功执行并返回相同的值。
    4. onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    5. // 5.如果 onRejected 不是函数且 promise1 拒绝执行, promise2 必须拒绝执行并返回相同的据因。
    6. onRejected =
    7. typeof onRejected === 'function'
    8. ? onRejected
    9. : reason => {
    10. throw reason;
    11. };
    12. return (newPromise = new AjPromise((resolve, reject) => {
    13. this.onFulfilledCallbacks.push(value => {
    14. try {
    15. let x = onFulfilled(value);
    16. resolvePromise(newPromise, x);
    17. } catch (e) {
    18. reject(e);
    19. }
    20. });
    21. this.onRejectedCallbacks.push(reason => {
    22. try {
    23. let x = onRejected(reason);
    24. resolvePromise(newPromise, x);
    25. } catch (e) {
    26. reject(e);
    27. }
    28. });
    29. }));
    30. }
    31. 复制代码

    1. then(onFulfilled, onRejected) {
    2. let newPromise;
    3. onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    4. onRejected =
    5. typeof onRejected === 'function'
    6. ? onRejected
    7. : reason => {
    8. throw reason;
    9. };
    10. // 2.2.6规范 对于一个promise,它的then方法可以调用多次.
    11. // 当在其他程序中多次调用同一个promise的then时 由于之前状态已经为FULFILLED / REJECTED状态,则会走以下逻辑,
    12. // 所以要确保为FULFILLED / REJECTED状态后 也要异步执行onFulfilled / onRejected ,这里使用setTimeout
    13. // 6.不论 promise1 被 reject 还是被 resolve 时 promise2 都会被 resolve,只有出现异常时才会被 rejected。
    14. // 由于在接下来的解决过程中需要调用resolve,reject进行处理,处理我们在调用处理过程时,传入参数
    15. if (this.state == FULFILLED) {
    16. return (newPromise = new AjPromise((resolve, reject) => {
    17. setTimeout(() => {
    18. try {
    19. let x = onFulfilled(this.value);
    20. resolvePromise(newPromise, x, resolve, reject);
    21. } catch (e) {
    22. reject(e);
    23. }
    24. });
    25. }));
    26. }
    27. if (this.state == REJECTED) {
    28. return (newPromise = new AjPromise((resolve, reject) => {
    29. setTimeout(() => {
    30. try {
    31. let x = onRejected(this.reason);
    32. resolvePromise(newPromise, x, resolve, reject);
    33. } catch (e) {
    34. reject(e);
    35. }
    36. });
    37. }));
    38. }
    39. if (this.state === PENDING) {
    40. return (newPromise = new AjPromise((resolve, reject) => {
    41. this.onFulfilledCallbacks.push(value => {
    42. try {
    43. let x = onFulfilled(value);
    44. resolvePromise(newPromise, x, resolve, reject);
    45. } catch (e) {
    46. reject(e);
    47. }
    48. });
    49. this.onRejectedCallbacks.push(reason => {
    50. try {
    51. let x = onRejected(reason);
    52. resolvePromise(newPromise, x, resolve, reject);
    53. } catch (e) {
    54. reject(e);
    55. }
    56. });
    57. }));
    58. }
    59. }
    60. 复制代码

    ok,完整的then方法搞定了。相信通过以上实践,你对返回要求已经有了更深的理解。

    2. Promise 解决过程

    Promise 解决过程是一个抽象的操作,其需输入一个 promise 和一个值,我们表示为 [Resolve],如果 x 有 then 方法且看上去像一个 Promise ,解决程序即尝试使 promise 接受 x 的状态;否则其用 x 的值来执行 promise 。

这种 thenable 的特性使得 Promise 的实现更具有通用性:只要其暴露出一个遵循 Promise/A+ 协议的 then 方法即可;这同时也使遵循 Promise/A+ 规范的实现可以与那些不太规范但可用的实现能良好共存。

运行 [Resolve] 需遵循以下步骤:
1。x 与 promise 相等
如果 promise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 promise。
2。x 为 Promise

  • 如果 x 为 Promise ,则使 promise 接受 x 的状态。
  • 如果 x 处于等待态, promise 需保持为等待态直至 x 被执行或拒绝。
  • 如果 x 处于执行态,用相同的值执行 promise。
  • 如果 x 处于拒绝态,用相同的据因拒绝 promise。

3。x 为对象或函数
如果 x 为对象或者函数:

  • 把 x.then 赋值给 then。
  • 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise。
  • 如果 then 是函数,将 x 作为函数的作用域 this 调用之。传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise:
    • 如果 resolvePromise 以值 y 为参数被调用,则运行 [Resolve]
    • 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
    • 如果 resolvePromise 和 rejectPromise 均被调用,或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
    • 如果调用 then 方法抛出了异常 e:
      • 如果 resolvePromise 或 rejectPromise 已经被调用,则忽略之
      • 否则以 e 为据因拒绝 promise
    • 如果 then 不是函数,以 x 为参数执行 promise
  • 如果 x 不为对象或者函数,以 x 为参数执行 promise

如果一个 promise 被一个循环的 thenable 链中的对象解决,而 [Resolve] 的递归性质又使得其被再次调用,根据上述的算法将会陷入无限递归之中。算法虽不强制要求,但也鼓励施者检测这样的递归是否存在,若检测到存在则以一个可识别的 TypeError 为据因来拒绝 promise 。
1.x 与 promise 相等

  1. function resolvePromise(promise2, x, resolve, reject) {
  2. //x 与 promise 相等
  3. //如果从onFulfilled中返回的x 就是promise2 就会导致循环引用报错
  4. //如果 promise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 promise
  5. if (x === promise2) {
  6. reject(new TypeError('循环引用'));
  7. }
  8. }
  9. 复制代码

2.x 为 Promise。

  1. function resolvePromise(promise2, x, resolve, reject) {
  2. if (x === promise2) {
  3. reject(new TypeError('循环引用'));
  4. }
  5. // x 为 Promise
  6. else if (x instanceof AjPromise) {
  7. // 如果 x 为 Promise ,则使 promise 接受 x 的状态
  8. // 如果 x 处于等待态, promise 需保持为等待态直至 x 被执行或拒绝
  9. if (x.state === PENDING) {
  10. x.then(
  11. y => {
  12. resolvePromise(promise2, y, resolve, reject);
  13. },
  14. reason => {
  15. reject(reason);
  16. }
  17. );
  18. } else {
  19. // 如果 x 处于执行态,用相同的值执行 promise
  20. // 如果 x 处于拒绝态,用相同的据因拒绝 promise
  21. x.then(resolve, reject);
  22. }
  23. }
  24. }
  25. 复制代码

3.x 为对象或函数

  1. function resolvePromise(promise2, x, resolve, reject) {
  2. if (x === promise2) {
  3. reject(new TypeError('循环引用'));
  4. }
  5. if (x instanceof AjPromise) {
  6. if (x.state === PENDING) {
  7. x.then(
  8. y => {
  9. resolvePromise(promise2, y, resolve, reject);
  10. },
  11. reason => {
  12. reject(reason);
  13. }
  14. );
  15. } else {
  16. x.then(resolve, reject);
  17. }
  18. } else if (x && (typeof x === 'function' || typeof x === 'object')) {
  19. // 避免多次调用
  20. let called = false;
  21. try {
  22. //把 x.then 赋值给 then
  23. let then = x.then;
  24. if (typeof then === 'function') {
  25. // 如果 then 是函数,将 x 作为函数的作用域 this 调用之。
  26. // 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
  27. // 如果 resolvePromise 和 rejectPromise 均被调用,或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
  28. then.call(
  29. x,
  30. // 如果 resolvePromise 以值 y 为参数被调用,则运行[[Resolve]](promise, y)
  31. y => {
  32. if (called) return;
  33. called = true;
  34. resolvePromise(promise2, y, resolve, reject);
  35. },
  36. // 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
  37. r => {
  38. if (called) return;
  39. called = true;
  40. reject(r);
  41. }
  42. );
  43. }else {
  44. // 如果 then 不是函数,以 x 为参数执行 promise
  45. resolve(x);
  46. }
  47. } catch (e) {
  48. // 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
  49. // 如果调用 then 方法抛出了异常 e:
  50. // 如果 resolvePromise 或 rejectPromise 已经被调用,则忽略之
  51. // 否则以 e 为据因拒绝 promise
  52. if (called) return;
  53. called = true;
  54. reject(e);
  55. }
  56. } else {
  57. // 如果 x 不为对象或者函数,以 x 为参数执行 promise
  58. resolve(x);
  59. }
  60. }
  61. 复制代码

Ok~比较复杂的解决过程也让我们搞定了.接下来我们整合下代码

Promises/A+ 规范 完整代码

  1. const PENDING = 'pending';
  2. const FULFILLED = 'fulfilled';
  3. const REJECTED = 'rejected';
  4. class AjPromise {
  5. constructor(fn) {
  6. this.state = PENDING;
  7. this.value = null;
  8. this.reason = null;
  9. this.onFulfilledCallbacks = [];
  10. this.onRejectedCallbacks = [];
  11. const resolve = value => {
  12. if (value instanceof Promise) {
  13. return value.then(resolve, reject);
  14. }
  15. setTimeout(() => {
  16. if (this.state === PENDING) {
  17. this.state = FULFILLED;
  18. this.value = value;
  19. this.onFulfilledCallbacks.map(cb => {
  20. cb = cb(this.value);
  21. });
  22. }
  23. });
  24. };
  25. const reject = reason => {
  26. setTimeout(() => {
  27. if (this.state === PENDING) {
  28. this.state = REJECTED;
  29. this.reason = reason;
  30. this.onRejectedCallbacks.map(cb => {
  31. cb = cb(this.reason);
  32. });
  33. }
  34. });
  35. };
  36. try {
  37. fn(resolve, reject);
  38. } catch (e) {
  39. reject(e);
  40. }
  41. }
  42. then(onFulfilled, onRejected) {
  43. let newPromise;
  44. onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
  45. onRejected =
  46. typeof onRejected === 'function'
  47. ? onRejected
  48. : reason => {
  49. throw reason;
  50. };
  51. if (this.state === FULFILLED) {
  52. return (newPromise = new AjPromise((resolve, reject) => {
  53. setTimeout(() => {
  54. try {
  55. let x = onFulfilled(this.value);
  56. resolvePromise(newPromise, x, resolve, reject);
  57. } catch (e) {
  58. reject(e);
  59. }
  60. });
  61. }));
  62. }
  63. if (this.state === REJECTED) {
  64. return (newPromise = new AjPromise((resolve, reject) => {
  65. setTimeout(() => {
  66. try {
  67. let x = onRejected(this.reason);
  68. resolvePromise(newPromise, x, resolve, reject);
  69. } catch (e) {
  70. reject(e);
  71. }
  72. });
  73. }));
  74. }
  75. if (this.state === PENDING) {
  76. return (newPromise = new AjPromise((resolve, reject) => {
  77. this.onFulfilledCallbacks.push(value => {
  78. try {
  79. let x = onFulfilled(value);
  80. resolvePromise(newPromise, x, resolve, reject);
  81. } catch (e) {
  82. reject(e);
  83. }
  84. });
  85. this.onRejectedCallbacks.push(reason => {
  86. try {
  87. let x = onRejected(reason);
  88. resolvePromise(newPromise, x, resolve, reject);
  89. } catch (e) {
  90. reject(e);
  91. }
  92. });
  93. }));
  94. }
  95. }
  96. }
  97. function resolvePromise(promise2, x, resolve, reject) {
  98. if (x === promise2) {
  99. reject(new TypeError('循环引用'));
  100. }
  101. if (x instanceof AjPromise) {
  102. if (x.state === PENDING) {
  103. x.then(
  104. y => {
  105. resolvePromise(promise2, y, resolve, reject);
  106. },
  107. reason => {
  108. reject(reason);
  109. }
  110. );
  111. } else {
  112. x.then(resolve, reject);
  113. }
  114. } else if (x && (typeof x === 'function' || typeof x === 'object')) {
  115. let called = false;
  116. try {
  117. let then = x.then;
  118. if (typeof then === 'function') {
  119. then.call(
  120. x,
  121. y => {
  122. if (called) return;
  123. called = true;
  124. resolvePromise(promise2, y, resolve, reject);
  125. },
  126. r => {
  127. if (called) return;
  128. called = true;
  129. reject(r);
  130. }
  131. );
  132. } else {
  133. resolve(x);
  134. }
  135. } catch (e) {
  136. if (called) return;
  137. called = true;
  138. reject(e);
  139. }
  140. } else {
  141. resolve(x);
  142. }
  143. }
  144. AjPromise.deferred = function() {
  145. let defer = {};
  146. defer.promise = new AjPromise((resolve, reject) => {
  147. defer.resolve = resolve;
  148. defer.reject = reject;
  149. });
  150. return defer;
  151. };
  152. module.exports = AjPromise;
  153. 复制代码

再来看看我们的实现是否符合Promises/A+规范

npm run test
复制代码

nice,测试用例全部通过!