简体中文 | English
✨ ES2021 Promise 的实现,基于 ES3 语法拥有超高兼容性,并遵从 ECMA-262 与 Promises/A+ 标准
学习
Promise
的最佳方式是实现它。
- 基于 ES3,几乎所有浏览器都受支持;
- 遵从 ECMA-262 与 Promises/A+ 标准,并通过 Promises/A+ 合规性测试,以及其它相关测试;
- 实现 ES2018、ES2020、ES2021 中关于 Promise 的新特性;
能力 | 版本 | 支持 |
---|---|---|
new Promise(executor) | ES2015 | ✔ |
Promise.prototype.then(onFulfilled, onRejected) | ES2015 | ✔ |
Promise.prototype.catch(onRejected) | ES2015 | ✔ |
Promise.prototype.finally(onFinally) | ES2018 | ✔ |
Promise.resolve(value) | ES2015 | ✔ |
Promise.reject(reason) | ES2015 | ✔ |
Promise.all(iterable) | ES2015 | ✔ |
Promise.race(iterable) | ES2015 | ✔ |
Promise.allSettled(iterable) | ES2020 | ✔ |
Promise.any(iterable) | ES2021 | ✔ |
npm i -S promise-for-es
- 作为 polyfill
// ES Module
import 'promise-for-es/polyfill';
// CommonJS
require('promise-for-es/polyfill');
- 作为 ponyfill
// ES Module
import Promise from 'promise-for-es';
// CommonJS
const Promise = require('promise-for-es');
以下面的代码为例:
const executor = (resolutionFunc, rejectionFunc) => {
// 业务逻辑
};
const p1 = new Promise(executor);
p1.then(onFulfilled, onRejected);
- 创建一个新的 Promise 对象
p2
; - 检查
p1
的状态:- 若是 "pending",将
onFulfilled
添加到p1
的 fulfill list,onRejected
添加到 reject list ; - 若是 "fulfilled",以
onFulfilled
、p2
、p1
的结果 新建一个微任务; - 若是 "rejected",以
onRejected
、p2
、p1
的结果 新建一个微任务;
- 若是 "pending",将
- 返回
p2
;
- 创建解析函数:
resolutionFunc
、rejectionFunc
; - 以
resolutionFunc
、rejectionFunc
作为参数调用executor
;
- 若任意解析函数已被调用,返回;
- 若
value
是 thenable,以value
新建一个微任务,并返回; - 改变
p1
的状态为 "fulfilled"; - 为 fulfill list 的每个元素新建一个微任务;
- 若任意解析函数已被调用,返回;
- 改变
p1
的状态为 "rejected"; - 为 reject list 的每个元素新建一个微任务;
npm run test:aplus
运行 Promises/A+ 合规性测试;npm run test:es6
运行 promises-es6-tests;npm run test:core-js
运行 core-js 关于 Promise 的相关测试;