promise-for-es
v1.0.0
Published
A ES2021 Promise implementation based on ES3 has high compatibility, and comply with ECMA-262 and Promises/A+
Downloads
236
Maintainers
Readme
简体中文 | English
Promise For ES
✨ A ES2021 Promise implementation based on ES3 has high compatibility, and comply with ECMA-262 and Promises/A+
The best way to learn
Promise
is to implement it.
Feature
- Base on ES3, almost all browsers are supported;
- Comply with ECMA-262 and Promises/A+, pass the Promises/A+ compliance test, and other related tests;
- Implement the new features about Promise of ES2018、ES2020、ES2021;
Support
|Ability|Version|Support| |-|:-:|:-:| |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|✔|
Install
npm i -S promise-for-es
Usage
- As a polyfill
// ES Module
import 'promise-for-es/polyfill';
// CommonJS
require('promise-for-es/polyfill');
- As a ponyfill
// ES Module
import Promise from 'promise-for-es';
// CommonJS
const Promise = require('promise-for-es');
Core logic
Using the example below:
const executor = (resolutionFunc, rejectionFunc) => {
// business logic
};
const p1 = new Promise(executor);
p1.then(onFulfilled, onRejected);
p1.then(onFulfilled, onRejected)
- Create a new Promise object
p2
; - Check the state of
p1
:- If "pending", push
onFulfilled
into the fulfill list ofp1
, and pushonRejected
into the reject list; - If "fulfilled", create a micro task with
onFulfilled
,p2
and the result ofp1
; - If "rejected", create a micro task with
onRejected
,p2
and the result ofp1
;
- If "pending", push
- return
p2
;
new Promise(executor)
- Create the resolving functions:
resolutionFunc
,rejectionFunc
; - Call
executor
withresolutionFunc
andrejectionFunc
as the arguments;
resolutionFunc(value)
- If any resolving function has been called, return;
- If
value
is thenable, create a micro task withvalue
, return; - Change the state of
p1
to "fulfilled"; - Create a micro task for each element of fulfill list;
rejectionFunc(reason)
- If any resolving function has been called, return;
- Change the state of
p1
to "rejected"; - Create a micro task for each element of reject list;
Test
npm run test:aplus
to run Promises/A+ compliance test;npm run test:es6
to run promises-es6-tests;npm run test:core-js
to run the core-js tests about Promise;
Reference
- ECMA-262
- Promises/A+