在阅读本篇文章之前,建议先阅读我的上一篇关于promise/A+规范的文章,方便与理解和掌握promise的实现思路与规范
平常我们用promise都是用new promise(),所以我们自己手写也应该用构造函数或者class类来实现,这里将用class来实现
class MPromise {
constructor() {
}
}
promise有三种状态,pending,fulfilled(resolved),rejected。这三种状态有两个特性。
- 初始状态为pending,状态唯一
- 一旦状态从pending=>fulfilled或者是pending=>rejected,状态将不可再次更改
我们给MPromise加上这三个常量状态值,并且定义初始值status来表示MPromise的状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MPromise {
constructor() {
// 初始状态为pending
this.status = PENDING;
}
}
一般的promise有两个回调resolve和reject方法
- 根据promise/A+规范,这两个方法是要更改status的,从pending改到fulfilled/rejected。
- 注意两个函数的入参分别是value和reason。
class MPromise {
constructor() {
// 初始状态为pending
this.status = PENDING;
//成功回调value
this.value = null;
//失败回调reason
this.reason = null;
}
resolve(value) {
if (this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
}
}
reject(reason) {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
}
}
}
到这一步,小伙伴们是不是发现了我们得promise少了入参,我们来补充一下
- 入参是一个函数,函数接受resolve和reject两个参数
- 注意在初始化promise的时候,就要执行这个函数,并且有任何报错都要通过reject抛出去
class MPromise{
constructor(fun){
this.status=PENDING;
this.value=null;
this.reason=null;
//如果两个方法都没调用,调用reject,把status改成REJECTED
try{
fn(this.resolve.bind(this),this.reject.bind(this));
}catch(e){
this.reject(e);
}
}
resolve(value){
//状态唯一,且只能从PENDING到FUFILLED,所以这里加判断
if(this.status==='PENDING'){
this.status='FUFILLED';
this.value=value;
}
}
reject(reason){
if(this.status==='PENDING'){
this.status='REJECTED';
this.reason=reason;
}
}
}
两个改变MPromise状态的方法已经实现了,接下来实现以下关键的then方法
- then接收两个参数,onFulfilled和onRejected
then(onFulfilled,onRejected){}
检查并处理参数,之前提到的不是function,则忽略,这个忽略指的是原样返回value或者reason。
这里我们定义一个可以判断参数类型的方法isFunction
isFunction(param){
return typeof param==='function';
}
then(onFulfilled,onRejeted){
const fulFilledFn=this.isFunction(onFulfilled)?onFulfilled:(value)=>{return value};
const rejectedFn=this.isFunction(onRejected)?onRejected:(reason)=>{throw reason}
//根据当前的promise的状态,调用不同的参数
switch(this.status){
case FULFILLED:{
fulFilledFn(this.value);
break;
}
case REJECTED:{
rejectedFn(this.reason);
break;
}
//因为promise是异步,如果这么写,当then方法一调用,就会瞬间执行,此时,status很有可能还是pending。
//我们首先得拿到所有的回调,然后才能在某个时机去执行他,这里我们新建两个数组,来分别储存成功和失败回调,调用then的时候,如果还是pending则存入数组。
case PENDING:{
this.FULFILLED_CALLBACK_LIST.push(realOnFulfilled);
this.REJECTED_CALLBACK_LIST.push(realOnRejected);
break;
}
}
}
在status发生变化的时候,就执行所有的回调,这里我们用一下es6的getter和setter,更为地符合语义,当status改变时,去做什么事。(当然也可以顺序执行,在给status赋值后,下面再加一行forEach)
get status(){
return this._status;
}
set status(newStatus){
switch(newStatus){
case FULFILLED:{
this.FULFILLED_CALLBACK_LIST.forEach(callback=>{
callback(this.value);
})
break;
}
case REJECTED: {
this.REJECTED_CALLBACK_LIST.forEach(callback => {
callback(this.reason);
});
break;
}
}
}
如果onFulfilled不是函数,且promise成功执行,promise2必须成功执行并返回相同的值
const fulFilledFnWithCatch = (resolve, reject) => {
try {
fulFilledFn(this.value);
resolve(this.value);
} catch (e) {
reject(e)
}
};
如果 onRejected 不是函数且 promise1 拒绝执行, promise2 必须拒绝执行并返回相同的据因。
需要注意的是,如果promise1的onRejected执行成功了,promise2应该被resolve
const rejectedFnWithCatch = (resolve, reject) => {
try {
rejectedFn(this.reason);
if (this.isFunction(onRejected)) {
resolve();
}
} catch (e) {
reject(e);
}
}
我们接着来处理then函数,此块内容比较多,我们单独来讨论。当onFulfilled或者onRejected抛出一个异常e,则promise2必须执行,并返回拒因e。这就要求我们手动catch代码,遇到报错返回reject
then(onFulfilled, onRejected) {
const fulFilledFn = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
return value;
}
const rejectedFn = this.isFunction(onRejected) ? onRejected : (reason) => {
throw reason;
};
//fulFilled状态的错误回调
const fulFilledFnWithCatch = (resolve, reject) => {
try {
fulFilledFn(this.value);
} catch (e) {
reject(e)
}
};
//rejected状态的回调
const rejectedFnWithCatch = (resolve, reject) => {
try {
rejectedFn(this.reason);
} catch (e) {
reject(e);
}
}
switch (this.status) {
case FULFILLED: {
return new MPromise(fulFilledFnWithCatch);
}
case REJECTED: {
return new MPromise(rejectedFnWithCatch);
}
case PENDING: {
return new MPromise((resolve, reject) => {
this.FULFILLED_CALLBACK_LIST.push(() => fulFilledFnWithCatch(resolve, reject));
this.REJECTED_CALLBACK_LIST.push(() => rejectedFnWithCatch(resolve, reject));
});
}
}
}
如果onFulfilled或者onRejected返回一个值x,则运行resolvePromise方法
const fulFilledFnWithCatch = (resolve, reject, newPromise) => {
try {
if (!this.isFunction(onFulfilled)) {
resolve(this.value);
} else {
const x = fulFilledFn(this.value);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e)
}
};
const rejectedFnWithCatch = (resolve, reject, newPromise) => {
try {
if (!this.isFunction(onRejected)) {
reject(this.reason);
} else {
const x = rejectedFn(this.reason);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e);
}
}
我们来定义一下resolvePromise方法
resolvePromise(newPromise, x, resolve, reject) {
// 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
// 这是为了防止死循环
if (newPromise === x) {
return reject(new TypeError('The promise and the return value are the same'));
}
if (x instanceof MPromise) {
// 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
// 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
// 这个if跟下面判断then然后拿到执行其实重复了,可有可无
x.then((y) => {
resolvePromise(newPromise, y, resolve, reject);
}, reject);
} else if (typeof x === 'object' || this.isFunction(x)) {
// 如果 x 为对象或者函数
// 这个坑是跑测试的时候发现的,如果x是null,应该直接resolve
if (x === null) {
return resolve(x);
}
let then = null;
try {
// 把 x.then 赋值给 then
then = x.then;
} catch (error) {
// 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
return reject(error);
}
// 如果 then 是函数
if (this.isFunction(then)) {
let called = false;
// 将 x 作为函数的作用域 this 调用之
// 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
// 名字重名了,我直接用匿名函数了
try {
then.call(
x,
// 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
(y) => {
// 如果 resolvePromise 和 rejectPromise 均被调用,
// 或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
// 实现这条需要前面加一个变量called
if (called) return;
called = true;
resolvePromise(promise, y, resolve, reject);
},
// 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
(r) => {
if (called) return;
called = true;
reject(r);
});
} catch (error) {
// 如果调用 then 方法抛出了异常 e:
// 如果 resolvePromise 或 rejectPromise 已经被调用,则忽略之
if (called) return;
// 否则以 e 为据因拒绝 promise
reject(error);
}
} else {
// 如果 then 不是函数,以 x 为参数执行 promise
resolve(x);
}
} else {
// 如果 x 不为对象或者函数,以 x 为参数执行 promise
resolve(x);
}
}
因为onFulfilled 和 onRejected 是微任务,所以我们应该用queueMicrotask包裹执行函数
const fulFilledFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onFulfilled)) {
resolve(this.value);
} else {
const x = fulFilledFn(this.value);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e)
}
})
};
const rejectedFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onRejected)) {
reject(this.reason);
} else {
const x = rejectedFn(this.reason);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e);
}
})
}
有then方法,我们这里再加一个catch方法,贴切我们原生的promise
catch (onRejected) {
return this.then(null, onRejected);
}
将现有对象转为Promise对象,如果 Promise.resolve 方法的参数,不是具有 then 方法的对象(又称 thenable 对象),则返回一个新的 Promise 对象,且它的状态为fulfilled。
static resolve(param) {
if (param instanceof MyPromise) {
return param;
}
return new MyPromise(function (resolve) {
resolve(param);
});
}
返回一个新的Promise实例,该实例的状态为rejected。Promise.reject方法的参数reason,会被传递给实例的回调函数。
static reject(reason) {
return new MPromise((resolve, reject) => {
reject(reason);
});
}
刚好,下午听到某只切图仔面试字节跳动,面试官让她手写promise.race方法,这里,我们基于上面封装好的MPromise来简单实现以下promise.race方法。首先,promise.race中
- const p = Promise.race([p1, p2, p3]);
- 该方法是将多个 Promise 实例,包装成一个新的 Promise 实例。
- 只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
static race(promiseList){
return new MPromise(resolve,reject)=>{
const len=promiseList.length;
if(len===0){
return resolve();
}
else{
for(let i=0;i<len;i++){
MPromise.resolve(promiseList[i]).then(
(value)=>{
return resolve(value);
}
(reason)=>{
return reject(reason);
}
))
)
}
}
}
}
完整代码如下
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MPromise {
FULFILLED_CALLBACK_LIST = [];
REJECTED_CALLBACK_LIST = [];
_status = PENDING;
constructor(fn) {
// 初始状态为pending
this.status = PENDING;
this.value = null;
this.reason = null;
try {
fn(this.resolve.bind(this), this.reject.bind(this));
} catch (e) {
this.reject(e);
}
}
get status() {
return this._status;
}
set status(newStatus) {
this._status = newStatus;
switch (newStatus) {
case FULFILLED: {
this.FULFILLED_CALLBACK_LIST.forEach(callback => {
callback(this.value);
});
break;
}
case REJECTED: {
this.REJECTED_CALLBACK_LIST.forEach(callback => {
callback(this.reason);
});
break;
}
}
}
resolve(value) {
if (this.status === PENDING) {
this.value = value;
this.status = FULFILLED;
}
}
reject(reason) {
if (this.status === PENDING) {
this.reason = reason;
this.status = REJECTED;
}
}
then(onFulfilled, onRejected) {
const fulFilledFn = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
return value;
}
const rejectedFn = this.isFunction(onRejected) ? onRejected : (reason) => {
throw reason;
};
const fulFilledFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onFulfilled)) {
resolve(this.value);
} else {
const x = fulFilledFn(this.value);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e)
}
})
};
const rejectedFnWithCatch = (resolve, reject, newPromise) => {
queueMicrotask(() => {
try {
if (!this.isFunction(onRejected)) {
reject(this.reason);
} else {
const x = rejectedFn(this.reason);
this.resolvePromise(newPromise, x, resolve, reject);
}
} catch (e) {
reject(e);
}
})
}
switch (this.status) {
case FULFILLED: {
const newPromise = new MPromise((resolve, reject) => fulFilledFnWithCatch(resolve, reject, newPromise));
return newPromise;
}
case REJECTED: {
const newPromise = new MPromise((resolve, reject) => rejectedFnWithCatch(resolve, reject, newPromise));
return newPromise;
}
case PENDING: {
const newPromise = new MPromise((resolve, reject) => {
this.FULFILLED_CALLBACK_LIST.push(() => fulFilledFnWithCatch(resolve, reject, newPromise));
this.REJECTED_CALLBACK_LIST.push(() => rejectedFnWithCatch(resolve, reject, newPromise));
});
return newPromise;
}
}
}
resolvePromise(newPromise, x, resolve, reject) {
// 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
// 这是为了防止死循环
if (newPromise === x) {
return reject(new TypeError('The promise and the return value are the same'));
}
if (x instanceof MPromise) {
// 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
// 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
x.then((y) => {
resolvePromise(newPromise, y, resolve, reject);
}, reject);
} else if (typeof x === 'object' || this.isFunction(x)) {
// 如果 x 为对象或者函数
if (x === null) {
// null也会被判断为对象
return resolve(x);
}
let then = null;
try {
// 把 x.then 赋值给 then
then = x.then;
} catch (error) {
// 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
return reject(error);
}
// 如果 then 是函数
if (this.isFunction(then)) {
let called = false;
// 将 x 作为函数的作用域 this 调用
// 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
try {
then.call(
x,
// 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
(y) => {
// 需要有一个变量called来保证只调用一次.
if (called) return;
called = true;
this.resolvePromise(promise, y, resolve, reject);
},
// 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
(r) => {
if (called) return;
called = true;
reject(r);
});
} catch (error) {
// 如果调用 then 方法抛出了异常 e:
if (called) return;
// 否则以 e 为据因拒绝 promise
reject(error);
}
} else {
// 如果 then 不是函数,以 x 为参数执行 promise
resolve(x);
}
} else {
// 如果 x 不为对象或者函数,以 x 为参数执行 promise
resolve(x);
}
}
catch (onRejected) {
return this.then(null, onRejected);
}
isFunction(param) {
return typeof param === 'function';
}
static resolve(value) {
if (value instanceof MPromise) {
return value;
}
return new MPromise((resolve) => {
resolve(value);
});
}
static reject(reason) {
return new MPromise((resolve, reject) => {
reject(reason);
});
}
static race(promiseList) {
return new MPromise((resolve, reject) => {
const length = promiseList.length;
if (length === 0) {
return resolve();
} else {
for (let i = 0; i < length; i++) {
MPromise.resolve(promiseList[i]).then(
(value) => {
return resolve(value);
},
(reason) => {
return reject(reason);
});
}
}
});
}
}