-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
122 lines (105 loc) · 2.29 KB
/
promise.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
/*
* :file description:
* :name: \hand-write-js\promise.js
* :author: PakJeon
* :copyright: (c) 2023, Tungee
* :date created: 2023-12-27 22:55:52
* :last editor: PakJeon
* :date last edited: 2023-12-27 23:00:58
*/
const STATUS = {
PENDING: 'PENDING',
FULFILLED: 'PENDING',
REJECTED: 'REJECTED',
}
function myPromise(executor) {
let self = this;
self.status = STATUS.PENDING;
self.value = null;
self.error = null;
self.onFulfilled = [];
self.onRejected = [];
const resolve = (val) => {
if (self.status !== STATUS.PENDING) {
return;
}
setTimeout(() => {
self.status = STATUS.FULFILLED;
self.value = val;
self.onFulfilled.forEach((item) => {
item(val);
});
});
}
const reject = (err) => {
if (self.status !== STATUS.PENDING) {
return;
}
setTimeout(() => {
self.status = STATUS.REJECTED;
self.error = err;
self.onRejected.forEach((item) => {
item(err);
})
})
}
executor(resolve, reject);
}
myPromise.prototype.then = (onFulfilled, onRejected) => {
if (this.status === STATUS.PENDING) {
this.onFulfilled.push(onFulfilled);
this.onRejected.push(onRejected);
} else if (this.status === STATUS.FULFILLED) {
onFulfilled(this.value);
} else if (this.status === STATUS.REJECTED) {
onRejected(this.error);
}
return this;
}
/**
* Promise.all
*/
function promiseAll(promises) {
return new Promise((resolve, reject) => {
if (typeof promises[Symbol.interator] !== 'function') {
return throw Error('must has interator');
}
const res = [];
let count = 0;
promises.forEach((promise) => {
Promise.resolve(promise).then((result) => {
res.push(result);
count++;
if (count === promises.length) {
resolve(res);
}
}).catch((err) => {
reject(err);
})
});
});
}
/**
* Promise.allSettled
*/
function promiseAllSettled(promises) {
return new Promise((resolve, reject) => {
if (typeof promises[Symbol.interator] !== 'function') {
throw Error('must be an array');
}
const res = [];
let count = 0;
promises.forEach((promise) => {
Promise.resolve(promise).then((result) => {
res.push({ status: 'fulfilled', value });
}).catch((error) => {
res.push({ status: 'rejected', error });
}).finnally(() => {
count++;
if (count === promises) {
resolve(res);
}
})
})
})
}