5 Star 15 Fork 3

Ambit / promise-for-es

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.zh-CN.md 3.38 KB
一键复制 编辑 原始数据 按行查看 历史
Ambit 提交于 2020-12-24 15:14 . docs: update
Promises/A+ logo

简体中文 | English

Promise For ES

✨ ES2021 Promise 的实现,基于 ES3 语法拥有超高兼容性,并遵从 ECMA-262 与 Promises/A+ 标准

学习 Promise 的最佳方式是实现它。

特性

  1. 基于 ES3,几乎所有浏览器都受支持;
  2. 遵从 ECMA-262 与 Promises/A+ 标准,并通过 Promises/A+ 合规性测试,以及其它相关测试;
  3. 实现 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

使用

  1. 作为 polyfill
// ES Module
import 'promise-for-es/polyfill';
// CommonJS
require('promise-for-es/polyfill');
  1. 作为 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);

p1.then(onFulfilled, onRejected)

  1. 创建一个新的 Promise 对象 p2
  2. 检查 p1 的状态:
    1. 若是 "pending",将 onFulfilled 添加到 p1fulfill listonRejected 添加到 reject list
    2. 若是 "fulfilled",以 onFulfilledp2p1 的结果 新建一个微任务;
    3. 若是 "rejected",以 onRejectedp2p1 的结果 新建一个微任务;
  3. 返回 p2 ;

new Promise(executor)

  1. 创建解析函数:resolutionFuncrejectionFunc
  2. resolutionFuncrejectionFunc 作为参数调用 executor;

resolutionFunc(value)

  1. 若任意解析函数已被调用,返回;
  2. valuethenable,以 value 新建一个微任务,并返回;
  3. 改变 p1 的状态为 "fulfilled";
  4. fulfill list 的每个元素新建一个微任务;

rejectionFunc(reason)

  1. 若任意解析函数已被调用,返回;
  2. 改变 p1 的状态为 "rejected";
  3. reject list 的每个元素新建一个微任务;

测试

  1. npm run test:aplus 运行 Promises/A+ 合规性测试;
  2. npm run test:es6 运行 promises-es6-tests
  3. npm run test:core-js 运行 core-js 关于 Promise 的相关测试;

参考

  1. ECMA-262
  2. Promises/A+
TypeScript
1
https://gitee.com/ambit/promise-for-es.git
git@gitee.com:ambit/promise-for-es.git
ambit
promise-for-es
promise-for-es
master

搜索帮助