-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPromisePolyfill.js
131 lines (113 loc) · 2.79 KB
/
PromisePolyfill.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class MyPromise {
constructor(executor) {
this.thenCb;
this.catchCb;
this.finallyCb;
this.thenData;
this.catchData;
this.state = "Pending";
this.resolve = (data) => {
if (this.thenCb) {
this.state = "Fulfulled";
this.thenCb(data);
if (this.finallyCb) {
this.finallyCb();
}
} else {
this.thenData = data;
}
};
this.reject = (err) => {
if (this.catchCb) {
this.state = "Rejected";
this.catchCb(err);
if (this.finallyCb) {
this.finallyCb();
}
} else {
this.catchData = err;
}
};
try {
executor(this.resolve, this.reject);
} catch (err) {
this.reject(err);
}
}
then(cb) {
if (this.state === "Pending" && this.thenData) {
this.state = "Fulfulled";
cb(this.thenData);
} else {
this.thenCb = cb;
}
return this;
}
catch(cb) {
if (this.state === "Pending" && this.catchData) {
this.state = "Rejected";
cb(this.catchData);
} else {
this.catchCb = cb;
}
return this;
}
finally(cb) {
if (this.state !== "Pending" && (this.thenData || this.catchData)) {
cb();
} else {
this.finallyCb = cb;
}
}
static resolve(value) {
return new MyPromise((resolve) => resolve(value));
}
static reject(value) {
return new MyPromise((resolve, reject) => reject(value))
}
static all(promises) {
return new MyPromise((resolve, reject) => {
if (!Array.isArray(promises)) {
return new TypeError("Promises type should be array");
}
let result = [];
let completedResponse = 0;
if (promises.length === 0) {
resolve(result);
}
promises.forEach((promise, index) => {
promise.then((res) => {
result.push(res);
completedResponse++;
if (completedResponse === promises.length) {
resolve(result);
}
}).catch((err) => {
reject(err);
});
});
});
}
}
const myPromise = new MyPromise((resolve, reject) => {
setTimeout(() => resolve("Hello, World!"), 1000);
});
// myPromise
// .then((data) => {
// console.log("On Then First : ", data);
// return "Hey";
// })
// // .then((secdata) => console.log("On Then Second : ",secdata))
// .catch((data) => console.log("On Catch : ", data))
// .finally(() => console.log("finally..."));
const promise1 = MyPromise.resolve(10);
const promise2 = MyPromise.resolve(20);
const promise3 = MyPromise.resolve(30);
// const promise3 = MyPromise.reject("Error while computing...");
MyPromise.all([myPromise, promise1, promise2, promise3])
.then((results) => {
console.log(results); // [10, 20, 30]
})
.catch((err) => {
console.error(err);
});