赞
踩
最近在看书学习的过程中,发现自己对 Promise 以及宏任务、微任务之间的关系还掌握得不够熟练,于是决定学习百家之长,自己动手实现一个 Promise,当然,就算如今这种行为已经烂了大街,我也想特立独行一些,于是就用上了 typescript 和 class。
首要的就是 Promise 独一无二的三个状态
type StatusType = 'pending' | 'fulfilled' | 'rejected';
然后是声明时需要传入的函数 executor
interface OnfulfilledType<T = unknown> {
(v?: T): unknown;
}
interface OnrejectedType {
(e?: Error): unknown;
}
interface ExecutorType<T = unknown> {
(resolve: OnfulfilledType<T>, reject: OnrejectedType): void;
}
这时候,我们就可以声明一个简单的 IPromise Class 了
class IPromise<T = unknown> { constructor(executor?: ExecutorType<T>) { // 为了尽量还原,所以 status 等属性不声明在 IPromise 对象上,这样就不会暴露出去 let status: StatusType = 'pending'; // 唯一状态 let value: unknown = null; // resolve 接收的值 let reason: Error = new Error('IPromise Error'); // reject 接收的值 const resolve: OnfulfilledType<T> = (v) => { if (status === 'pending') { status = 'fulfilled'; value = v; } }; const reject: OnrejectedType = (e) => { if (status === 'pending') { status = 'rejected'; if (e && isError(e)) { reason = e; } else { throw new Error('IPromise reason should be Error Type'); } } }; if (executor) { try { executor(resolve, reject); } catch (error) { reject(error); } } } }
new 一个对象试试
const promise: IPromise<string> = new IPromise((resolve) => {
resolve('promise'); // 这里如果传入 number 类型的参数会报错
});
好了,热身完成,开始真正实现 IPromise 的功能了。
想了想,Promise 对象有什么功能呢
返回一个状态为 fulfilled 的 Promise 实例
返回一个状态为 rejected 的 Promise 实例
接收一个 Promise 实例数组,并返回一个 resolve 出所有结果的 Promise 实例,有一个实例决议为 rejected,则会 reject 出错误
接收一个 Promise 实例数组,并返回一个 resolve 出首个结果的 Promise 实例
其中,resolve,reject,all 和 race 为 Promise 对象私有方法,不会被实例继承,所以用 static 实现
盘他!
type StatusType = 'pending' | 'fulfilled' | 'rejected'; interface OnfulfilledType<T = unknown> { (v?: T): unknown; } interface OnrejectedType { (e?: Error): unknown; } interface ExecutorType<T = unknown> { (resolve: OnfulfilledType<T>, reject: OnrejectedType): void; } interface ResolvePromiseType { (promise: IPromise, result: unknown, resolve: OnfulfilledType, reject: OnrejectedType): void; } const isFn = (fn: unknown) => typeof fn === 'function'; const isError = (e: unknown) => e instanceof Error; const onCorrect: OnfulfilledType = (v) => v; const onError: OnrejectedType = (e) => { throw e; }; const handleFnList = (fnList: Function[]) => { if (fnList.length) fnList.forEach((fn) => fn()); }; const resolvePromise: ResolvePromiseType = (promise, result, resolve, reject) => { if (result === promise) { reject(new Error('Chaining cycle detected for promise #<Promise>')); } else if (result instanceof IPromise) { result.then(resolve, reject); } else resolve(result); }; class IPromise<T = unknown> { static resolve = (v: unknown) => { if (v instanceof IPromise) return v; return new IPromise((resolve) => resolve(v)); }; static reject = (e: Error) => { return new IPromise((_, reject) => { if (isError(e)) reject(e); else { throw new TypeError('IPromise reason should be Error Type'); } }); }; static all = (promiseList?: IPromise[]) => { if (!Array.isArray(promiseList)) throw new TypeError('The argument should be an array!'); return new IPromise((resolve, reject) => { try { const results: unknown[] = []; promiseList.forEach((promise) => { if (promise instanceof IPromise) { promise.then((v) => { results.push(v); if (results.length === promiseList.length) resolve(results); }); } else reject(new TypeError('Every item of argument should be IPromise!')); }); } catch (error) { reject(error); } }); }; static race = (promiseList?: IPromise[]) => { if (!Array.isArray(promiseList)) throw new TypeError('The argument should be an array!'); return new IPromise((resolve, reject) => { try { const result: unknown[] = []; promiseList.forEach((promise) => { if (promise instanceof IPromise) { promise.then((v) => { if (!result.length) result.push(v); else resolve(result[0]); }); } else reject(new TypeError('Every item of argument should be IPromise!')); }); } catch (error) { reject(error); } }); }; then: (onfulfilled?: OnfulfilledType, onRejected?: OnrejectedType) => IPromise; catch: (catchFn: OnrejectedType) => IPromise; constructor(executor: ExecutorType<T>) { let status: StatusType = 'pending'; // 唯一状态 let value: unknown = null; // resolve 接收的值 let reason: Error = new Error('IPromise Error'); // reject 接收的值 // 如果初始化时的 resolve 是异步,则用数组来保存需要执行的方法 const onfulfilledList: OnfulfilledType[] = []; const onrejectedList: OnrejectedType[] = []; this.then = (onfulfilled = onCorrect, onRejected = onError) => { const promise = new IPromise((resolve, reject) => { const f = isFn(onfulfilled) ? onfulfilled : onCorrect; const r = isFn(onRejected) ? onRejected : onError; const newF = () => { queueMicrotask(() => { try { resolvePromise(promise, f(value), resolve, reject); } catch (error) { reject(error); } }); }; const newR = () => { queueMicrotask(() => { try { resolvePromise(promise, r(reason), resolve, reject); } catch (error) { reject(error); } }); }; if (status === 'fulfilled') newF(); if (status === 'rejected') newR(); if (status === 'pending') { onfulfilledList.push(newF); onrejectedList.push(newR); } }); return promise; }; this.catch = (catchFn) => this.then(undefined, catchFn); const resolve: OnfulfilledType<T> = (v) => { if (status === 'pending') { status = 'fulfilled'; value = v; handleFnList(onfulfilledList); } }; const reject: OnrejectedType = (e) => { if (status === 'pending') { status = 'rejected'; if (e && isError(e)) { reason = e; handleFnList(onrejectedList); } else { throw new Error('IPromise reason should be Error Type'); } } }; if (executor) { if (isFn(executor)) { try { executor(resolve, reject); } catch (error) { reject(error); } } else reject(new TypeError('new IPromise() should receive a Function argument!')); } else reject(new Error('new IPromise() should receive an arguments!')); } } export default IPromise;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。