标识符“Promise”重复。编译器在包含异步函数的模块的顶层范围中保留名称“Promise”。ts(2529)
import { ResolveType, RejectType, Executor } from './actionType'
function isObject(val: any): val is Record<any, any> {
return val !== null && typeof val === 'object'
}
function isFunction(data: any): data is Function {
return typeof data === 'function'
}
function isPromise(val: any): val is Promise {
return isObject(val) && isFunction(val.then)
}
class Promise<T = any> {
public reject: RejectType;
public resolve: ResolveType;
public status: string;
public resolve_value: any;
public reject_value: any;
// 保存成功状态要执行的函数
public resolve_then_callbacks: (() => void)[] = [];
// 保存失败状态要执行的函数
public reject_then_callbacks: (() => void)[] = [];
constructor(executor: Executor) {
this.status = "pending";
this.resolve = (value: any): any => {
if (this.status === "pending") {
this.status = "success";
this.resolve_value = value;
this.resolve_then_callbacks.forEach(callback => callback())
}
}
this.reject = (value: any): any => {
if (this.status === "pending") {
this.status = "full";
this.reject_value = value;
}
}
try {
executor(this.resolve, this.reject);
} catch (err) {
this.status = "pending";
this.reject(err.toString());
throw new Error('程序终止');
}
}
then(resolveInthen: ResolveType, rejectInthen: RejectType) {
console.log(`进入到then函数`);
return new Promise((resolve, reject) => {
let result: any;
if (this.status === "success") {
result = resolveInthen(this.resolve_value)
resolve(result)
}
if (this.status === "full") {
result = rejectInthen(this.reject_value)
reject(result)
}
if (this.status === "pending") {
this.processManyAsyncAndSync(resolveInthen, rejectInthen, resolve, reject)
}
})
}
/**
* 执行多个异步+多级then的处理方法
* @param resolveInthen
* @param rejectInthen
* @param resolve
* @param reject
*/
processManyAsyncAndSync(resolveInthen: ResolveType, rejectInthen: RejectType, resolve: RejectType, reject: RejectType) {
let result: any;
this.resolve_then_callbacks.push(async () => {
result = await resolveInthen(this.resolve_value);
if (isPromise(result)) {
resolve(result.resolve_value)
} else {
resolve(result)
}
console.log(`then中resolve函数参数执行结果`);
})
}
}
export { Promise }