-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomPromise.ts
More file actions
76 lines (66 loc) · 1.66 KB
/
customPromise.ts
File metadata and controls
76 lines (66 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
export default class MyPromise<T> {
private status = "pending";
private thenCallBacks: ((value: T) => any)[] = [];
private catchCallBacks: ((error: Error) => any)[] = [];
private successData?: T;
private failureData?: Error;
constructor(executor:(resolve:(data:T)=>any, reject:(err:Error)=>any)){
try{
executor(this.resolve,this.reject);
}
catch(e){
this.reject(e)
}
}
private resolve(data: T) {
if (data instanceof MyPromise) {
// call then method
} else {
queueMicrotask(() => {
if (this.status === "pending") {
(this.status = "fulfilled"), (this.successData = data);
this.thenCallBacks.forEach((cb) => cb(data));
}
});
}
}
private reject(error: Error) {
if (error instanceof MyPromise) {
// call then
} else {
queueMicrotask(() => {
if (this.status === "pending") {
this.status = "rejected";
this.failureData = error;
this.catchCallBacks.forEach((cb) => cb(error));
}
});
}
}
public then(
onFullFilled?: (data: T) => any,
onRejected?: (error: Error) => any
) {
const successCallBack = onFullFilled
? onFullFilled
: (data: unknown) => data;
const failureData = onRejected
? onRejected
: (err: Error) => {
throw err;
};
return new MyPromise((resolve,reject)=>{
const handle = (callback, args)=>{
try{
resolve(callback(args));
}
catch(e){
reject(e)
}
}
if(this.status==="pending"){
this.thenCallBacks.push(())
}
})
}
}