Promise的模拟实现
结构
promise经常使用的方法类似下边这样:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
从这个例子看来promise是作为构造函数使用,参数是一个function(暂且称为executor),通过调用then设置成功或者失败的回调函数,所以MyPromise的基本结构如下:
const MyPromise = function (executor) {
}
MyPromise.prototype.then=function () {}
模拟promise基本功能
继续上边的例子,我们来看看promise主要的工作流程:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
从上边例子可以看出promise通过then方法注册成功和失败的回调函数,然后在executor中通过resolve和reject给成功和失败的回调函数传递参数,然后调用。
下边就是模拟promsie的代码:
STATUS = {
SUCCESS: 'SUCCESS',
FAIL: 'FAIL',
PENDING: 'PENDING'
};
const MyPromise = function (executor) {
this.status = STATUS.PENDING; // 存储当前promise状态
this.onFulfilled = Function.prototype; // 存储成功的回调函数
this.onRejected = Function.prototype; // 存储失败的回调函数
this.value = '';
this.error = '';
const resolve = (value) => {
if (value instanceof MyPromise) {
return MyPromise.then(resolve, reject)
}
setTimeout(() => {
if (this.status === STATUS.PENDING) {
this.status = STATUS.SUCCESS;
this.value = value;
this.onFulfilled(this.value);
}
}, 20)
};
const reject = (error) => {
if (error instanceof MyPromise) {
return MyPromise.then(resolve, reject)
}
setTimeout(() => {
if (this.status === STATUS.PENDING) {
this.status = STATUS.FAIL;
this.error = error;
this.onRejected(this.error);
}
}, 20)
};
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}
};
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (data) => data;
onRejected = typeof onRejected === 'function' ? onRejected : (error) => { throw error};
if (this.status === STATUS.SUCCESS) {
this.onFulfilled(this.value)
} else if (this.status === STATUS.FAIL) {
this.onRejected(this.error);
} else if (this.status === STATUS.PENDING) {
this.onFulfilled = onFulfilled;
this.onRejected = onRejected;
}
};
在构造函数中设置resolve和reject方法,当调用这两个方法会将参数存在对象中供成功或者失败回调函数调用,resolve会将值存在value中,reject会将值存在error中,然后调用对应状态的回调函数。
在then方法中进行判断:
- 如果promise处于pending状态就给promise注册回调函数
- 如果成功或者失败则直接调用回调函数将promise中的value或者error传过去。
这块注意点:
- resolve和reject函数中使用了setTimeout,作用是确保调用的时候回调函数已经挂载在对象上了
- resolve和reject函数中加入了状态判断是因为promise在状态一旦进入失败或者成功后状态
就不可更改了
。
完善promise多次挂载
promise允许多次挂载例如下边这种情况:
let promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('data')
}, 2000)
})
promise.then(data => {
console.log(`1: ${data}`)
})
promise.then(data => {
console.log(`2: ${data}`)
})
promise通过then方法挂载了两个成功回调函数,按照上边的方法并不能完成这个需求,所以加了一些修改:
STATUS = {
SUCCESS: 'SUCCESS',
FAIL: 'FAIL',
PENDING: 'PENDING'
};
const MyPromise = function (executor) {
this.status = STATUS.PENDING;
// 将回调函数改为一个数组
this.onFulfilledArray = [];
this.onRejectedArray = [];
this.value = '';
this.error = '';
const resolve = (value) => {
if (value instanceof MyPromise) {
return MyPromise.then(resolve, reject)
}
setTimeout(() => {
if (this.status === STATUS.PENDING) {
this.status = STATUS.SUCCESS;
this.value = value;
this.onFulfilledArray.forEach((func) => {
func(this.value);
});
}
}, 20)
};
const reject = (error) => {
if (error instanceof MyPromise) {
return MyPromise.then(resolve, reject)
}
setTimeout(() => {
if (this.status === STATUS.PENDING) {
this.status = STATUS.FAIL;
this.error = error;
this.onRejectedArray.forEach((func) => {
func(this.error);
});
}
}, 20)
};
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}
};
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (data) => data;
onRejected = typeof onRejected === 'function' ? onRejected : (error) => { throw error};
if (this.status === STATUS.SUCCESS) {
onFulfilled(this.value);
} else if (this.status === STATUS.FAIL) {
onRejected(this.error);
}else if (this.status === STATUS.PENDING) {
this.onFulfilledArray.push(onFulfilled);
this.onRejectedArray.push(onRejected);
}
};
promise去掉成功或者失败回调函数存储,改为使用数组存储成功和失败的回调,然后,在then函数中如果promise状态是pending就将回调函数加入数组中存储下,接着修改了resolve和reject方法,不是直接调用回调函数然后穿参而是遍历回调函数数组依次执行。
链式调用
promise的then是支持链式调用的,then方法依然会返回promise,就像下边这样:
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('lucas')
}, 2000)
})
promise.then(data => {
console.log(data)
return `${data} next then`
})
.then(data => {
console.log(data) // lucas next then
})
因此代码还需要进一步完善,then要返回promise,then方法修改为如下:
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (data) => data;
onRejected = typeof onRejected === 'function' ? onRejected : (error) =>{ throw error};
let promise = null;
if (this.status === STATUS.SUCCESS) {
promise = new MyPromise((resolve, reject) => {
setTimeout(() => { // 保持resolve操作在then后边
try {
resolve(onFulfilled(this.value));
} catch (e) {
reject(e);
}
})
});
return promise;
} else if (this.status === STATUS.FAIL) {
promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
resolve(onRejected(this.error));
} catch (e) {
reject(e);
}
})
});
return promise;
} else if (this.status === STATUS.PENDING) {
promise = new MyPromise((resolve, reject) => {
this.onFulfilledArray.push((value) => {
try {
resolve(onFulfilled(value));
} catch (e) {
reject(e);
}
});
this.onRejectedArray.push((error) => {
try {
reject(onRejected(error));
} catch (e) {
reject(e);
}
});
});
return promise;
}
};
难点在于pending状态下的处理,这里使用了闭包的思想,在给回调函数缓存数组中存入回调函数的时候,闭包会存下promise返回值的resolve和reject方法与then方法的两个回调函数,这样在promise的resolve与reject方法调用回调函数的时候,会从闭包中取出对应的内容,完成功能。
链式调用处理then方法直接返回promise的情况
上边的例子中没有处理then方法回调函数如果直接返回一个promise的情况,例子如下:
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('lucas')
}, 2000)
})
promise.then(data => {
console.log(data)
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${data} next then`)
}, 4000)
})
})
.then(data => {
console.log(data)
})
这种情况在promise中会解构promise返回,所以上边代码需要进行处理,加入对于返回值是promise的解构处理。
then方法修改为下边这样:
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (data) => data;
onRejected = typeof onRejected === 'function' ? onRejected : (error) => { throw error};
let promise = null;
if (this.status === STATUS.SUCCESS) {
promise = new MyPromise((resolve, reject) => {
setTimeout(() => { // 保持resolve操作在then后边
try {
resolvePromiseResult(promise, onFulfilled(this.value), resolve, reject);
} catch (e) {
reject(e);
}
})
});
return promise;
} else if (this.status === STATUS.FAIL) {
promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
try {
resolvePromiseResult(promise, onRejected(this.error), resolve, reject);
} catch (e) {
reject(e);
}
})
});
return promise;
} else if (this.status === STATUS.PENDING) {
promise = new MyPromise((resolve, reject) => {
this.onFulfilledArray.push((value) => {
try {
resolvePromiseResult(promise, onFulfilled(value), resolve, reject);
} catch (e) {
reject(e);
}
});
this.onRejectedArray.push((error) => {
try {
resolvePromiseResult(promise, onRejected(error), resolve, reject);
} catch (e) {
reject(e);
}
});
});
return promise;
}
};
这里添加了一个方法将promise和返回值与resolve和reject作为参数传递了进去,在方法内部进行处理。
添加方法的完整代码如下:
function resolvePromiseResult(promise, result, resolve, reject) {
if (result instanceof MyPromise) {
if (result.status === STATUS.PENDING) {
result.then((data) => {
resolvePromiseResult(promise, data, resolve, reject);
}, reject)
} else {
result.then(resolve, reject);
}
return;
}
const isComplexObject = (typeof result === 'function' || typeof result === 'object') && result !== null;
if (isComplexObject) {
try {
const thenable = result.then;
if (typeof thenable === 'function') {
thenable.call(result, (data) => {
return resolvePromiseResult(promise, data, resolve, reject);
}, (error) => {
return reject(error);
})
} else {
resolve(result);
}
} catch (e) {
return reject(e);
}
} else {
resolve(result);
}
}
代码重点如下:
- 首先对与result是promise进行处理,当promise是pending状态,进行递归调用,如果是success后者fail状态直接改变promise状态传递给resolve与reject函数回调。
2.针对result如果是类promise处理,与promise对象一样的处理方式
promise 静态方法实现
catch
catch方法很简单
MyPromise.prototype.catch = function(catchFunc) {
return this.then(null, catchFunc)
}
成功的情况我们不处理只处理错误的情况
Promise.resolve与Promise.reject模拟
resolve与reject静态方法也很简单就是返回一个给定值的promise
MyPromise.resolve = function (value) {
return new MyPromise((resolve, reject) => {
resolve(value)
})
};
MyPromise.reject = function (value) {
return new MyPromise((resolve, reject) => {
reject(value)
})
};
Promise.all与 Promise.race模拟
promise的all方法是用来处理多个promise的方法,参数是个promise数组,当所有promise完成后会返回一个数组,存储每个promise的返回结果,模拟代码也很简单,如下:
MyPromise.all = function (promiseArray) {
if (!Array.isArray(promiseArray)) {
throw new Error('The arguments should be an array!')
}
return new MyPromise((resolve, reject) => {
try {
let resultArray = [];
const length = promiseArray.length;
for (let i = 0; i < length; i++) {
promiseArray[i].then(data => {
resultArray.push(data);
if (resultArray.length === length) {
resolve(resultArray)
}
}, reject)
}
} catch (e) {
reject(e)
}
}
)
}
race方法是当第一个promsie返回后就返回结果,参数也是一个promise数组,实现方法也非常简单,代码如下:
MyPromise.race = function (promiseArray) {
if (!Array.isArray(promiseArray)) {
throw new TypeError('The arguments should be an array!')
}
return new MyPromise((resolve, reject) => {
try {
const length = promiseArray.length
for (let i = 0; i < length; i++) {
promiseArray[i].then(resolve, reject)
}
} catch (e) {
reject(e)
}
})
}
道理也很简单就是在第一个promsie响应的时候就返回结果终止订阅。
结束语
本篇文章尝试模拟一个promise,借此来深入理解下这个js常用且很重要的功能,分享出来希望可以帮助和我一样的前端小白,很多地方实现可能不够严谨,或者可能存在错误,欢迎大家指正。