File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ class MyPromise {
2+ constructor ( executor ) {
3+ this . thenCb ;
4+ this . catchCb ;
5+ this . finallyCb ;
6+ this . thenData ;
7+ this . catchData ;
8+ this . state = "Pending" ;
9+
10+ this . resolve = ( data ) => {
11+ if ( this . thenCb ) {
12+ this . state = "Fulfulled" ;
13+ this . thenCb ( data ) ;
14+ if ( this . finallyCb ) {
15+ this . finallyCb ( ) ;
16+ }
17+ } else {
18+ this . thenData = data ;
19+ }
20+ } ;
21+
22+ this . reject = ( err ) => {
23+ if ( this . catchCb ) {
24+ this . state = "Rejected" ;
25+ this . catchCb ( err ) ;
26+ if ( this . finallyCb ) {
27+ this . finallyCb ( ) ;
28+ }
29+ } else {
30+ this . catchData = err ;
31+ }
32+ } ;
33+
34+ try {
35+ executor ( this . resolve , this . reject ) ;
36+ } catch ( err ) {
37+ this . reject ( err ) ;
38+ }
39+ }
40+
41+ then ( cb ) {
42+ if ( this . state === "Pending" && this . thenData ) {
43+ this . state = "Fulfulled" ;
44+ cb ( this . thenData ) ;
45+ } else {
46+ this . thenCb = cb ;
47+ }
48+ return this ;
49+ }
50+
51+ catch ( cb ) {
52+ if ( this . state === "Pending" && this . catchData ) {
53+ this . state = "Rejected" ;
54+ cb ( this . catchData ) ;
55+ } else {
56+ this . catchCb = cb ;
57+ }
58+
59+ return this ;
60+ }
61+
62+ finally ( cb ) {
63+ if ( this . state !== "Pending" && ( this . thenData || this . catchData ) ) {
64+ cb ( ) ;
65+ } else {
66+ this . finallyCb = cb ;
67+ }
68+ }
69+ }
70+
71+ const myPromise = new MyPromise ( ( resolve , reject ) => {
72+ setTimeout ( ( ) => reject ( "Hello, World!" ) , 1000 ) ;
73+ } ) ;
74+
75+ myPromise
76+ . then ( ( data ) => {
77+ console . log ( "On Then First : " , data ) ;
78+ return "Hey" ;
79+ } )
80+ // .then((secdata) => console.log("On Then Second : ",secdata))
81+ . catch ( ( data ) => console . log ( "On Catch : " , data ) )
82+ . finally ( ( ) => console . log ( "finally..." ) ) ;
You can’t perform that action at this time.
0 commit comments