1. Promise A+ 规范
-
官方英文地址:https://promisesaplus.com/
-
中文翻译可参考 http://malcolmyu.github.io/malnote/2015/06/12/Promises-A-Plus/
2. 代码实现
github地址:https://github.com/whu-luojian/Promise.git
// promise的状态枚举
const STATUS = {
PENDING: 0,
FULFILLED: 1,
REJECTED: 2
}
class Promise {
constructor(task) {
// promise初始状态
this.status = STATUS.PENDING;
// resolve时返回的数据
this.resolveData = null;
// reject时返回的数据
this.rejectData = null;
// resolve和reject时执行的回调队列
// promise的resolve和reject为异步响应时,即调用then时promise为
// pending状态,则将传入then的函数加入该队列,等待promise resolve或
// reject时执行该队列
this.onFulfilledList = [];
this.onRejectedList = [];
/**
* promise成功,执行onFulfilledList回调
* @param {*} data
*/
this.onResolve = (data) => {
if(this.status === STATUS.PENDING) {
this.status = STATUS.FULFILLED;
this.resolveData = data;
this.onFulfilledList.forEach(fn => {
fn(this.resolveData)
})
}
}
/**
* promise失败,执行onRejectedList回调
* @param {*} err
*/
this.onReject = (err) => {
if(this.status === STATUS.PENDING) {
this.status = STATUS.REJECTED;
this.rejectData = err;
this.onRejectedList.forEach(fn => {
fn(this.rejectData)
})
}
}
/**
* promise解析, 根据then 返回数据类型不同封装不同的promise
* 返回,以便实现then的链式调用及Promise的thenable特性
* @param {*当前then return数据} data
* @param {*当前then的resolve} resolve
* @param {*当前then的reject} reject
*/
this.resolvePromise = (data, resolve, reject) => {
// then return 的数据是一个promise
if(data instanceof Promise) {
if(data.status === STATUS.PENDING) {
data.then((val) => {
this.resolvePromise(val, resolve, reject);
}, reject)
} else if (data.status === STATUS.FULFILLED) {
resolve(data.resolveData)
} else {
reject(data.rejectData)
}
}
// then return的是一个对象,若对象具有then方法,则可使用此方法作为新的then
// Promise的thenable特性基于此
else if(data !== null && data instanceof Object) {
try {
let then = data.then