-
Notifications
You must be signed in to change notification settings - Fork 1
/
promise.js
executable file
·270 lines (242 loc) · 6.42 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const PENDING = "PENDING";
const FULFILED = "FULFILED";
const REJECTED = "REJECTED";
const isPromise = (x) => x instanceof Promise;
const isThenable = (x) =>
x !== null &&
(typeof x === "function" || typeof x === "object") &&
typeof x.then === "function";
function handlePromiseOrThenable(promise, x, resolve, reject) {
if (promise === x) {
throw new Error("自身嵌套调用");
}
if (isPromise(x)) {
if (x.state === PENDING) {
x.then((y) => y).then(
(y) => handlePromiseOrThenable(promise, y, resolve, reject),
reject
);
} else {
x.state === FULFILED && resolve(x.value);
x.state === REJECTED && reject(x.value);
}
return;
}
if (isThenable(x)) {
x.then((y) => handlePromiseOrThenable(promise, y, resolve, reject), reject);
} else {
resolve(x);
}
}
class Promise {
constructor(fn) {
this.state = PENDING;
this.value = null;
this.resolveCallbacks = [];
this.rejectCallbacks = [];
const resolve = (value) => {
if (isPromise(value) || isThenable(value)) {
return handlePromiseOrThenable(this, value, resolve, reject);
}
setTimeout(() => {
this.value = value;
this.state = FULFILED;
for (const callback of this.resolveCallbacks) {
callback(value);
}
}, 0);
};
const reject = (value) => {
if (isPromise(value) || isThenable(value)) {
return handlePromiseOrThenable(this, value, resolve, reject);
}
setTimeout(() => {
this.value = value;
this.state = REJECTED;
for (const callback of this.rejectCallbacks) {
callback(value);
}
}, 0);
};
fn(resolve, reject);
}
then(
onResolve = (...args) => args,
onReject = (err) => {
throw new Error(err);
}
) {
let promise;
if (this.state === PENDING) {
promise = new Promise((resolve, reject) => {
this.resolveCallbacks.push((value) => {
const x = onResolve(value);
handlePromiseOrThenable(promise, x, resolve, reject);
});
this.rejectCallbacks.push((value) => {
const x = onReject(value);
handlePromiseOrThenable(promise, x, resolve, reject);
});
});
}
if (this.state === FULFILED) {
promise = new Promise((resolve, reject) => {
this.resolveCallbacks.push((value) => {
const x = onResolve(value);
handlePromiseOrThenable(promise, x, resolve, reject);
});
});
}
if (this.state === REJECTED) {
promise = new Promise((resolve, reject) => {
this.rejectCallbacks.push((value) => {
const x = onReject(value);
handlePromiseOrThenable(promise, x, resolve, reject);
});
});
}
return promise;
}
catch(
onReject = (err) => {
throw new Error(err);
}
) {
return this.then(undefined, onReject);
}
finally(callback = (...args) => args) {
return this.then(
(data) => Promise.resolve(callback()).then(() => data),
(reason) =>
Promise.reject(callback()).then(() => {
throw new Error(reason);
})
);
}
static all(promises) {
return new Promise((resolve, reject) => {
let finishCount = 0;
let res = [];
let len = promises.length;
for (let i = 0; i < len; i++) {
Promise.resolve(promises[i]).then((data) => {
finishCount++;
res[i] = data;
if (len === finishCount) {
resolve(res);
}
});
}
});
}
static allSettled(promises) {
return new Promise((resolve) => {
let count = 0;
let res = [];
for (const promise of promises) {
Promise.resolve(promise).then(
(data) => {
res.push({
state: FUlFILLED,
value: data,
});
count++;
if (count === promises.length) {
resolve(res);
}
},
(reason) => {
res.push({
state: REJECTED,
value: reason,
});
count++;
if (count === promises.length) {
resolve(res);
}
}
);
}
});
}
static race(promises) {
return new Promise((resolve, reject) => {
for (const promise of promises) {
Promise.resolve(promise).then(resolve, reject);
}
});
}
static resolve(data) {
if (isPromise(data)) return data;
if (isThenable(data))
return new Promise((resolve, reject) => data.then(resolve, reject));
return new Promise((resolve) => resolve(data));
}
static reject(reason) {
return new Promise((_, reject) => reject(reason));
}
static limit(count) {
let queue = [],
working = 0;
function addTask(asyncTask) {
return new Promise((resolve, reject) => {
asyncTask.resolve = resolve;
asyncTask.reject = reject;
if (working >= count) {
queue.push(asyncTask);
} else {
runTask(asyncTask);
}
});
}
function runTask(asyncTask) {
working++;
Promise.resolve(asyncTask()).then((data) => {
working--;
asyncTask.resolve(data);
if (queue.length) {
runTask(queue.shift());
}
});
}
return addTask;
}
}
// new Promise((resolve, reject) => {
// resolve(Promise.resolve());
// })
// .then(() => console.log("promise1"))
// .then(() => console.log("promise2"))
// .then(() => Promise.resolve())
// .then(() => console.log("promise4"))
// .then(() => console.log("promise5"));
// new Promise((resolve, reject) => {
// resolve();
// })
// .then(() => console.log("promise6"))
// .then(() => console.log("promise7"))
// .then(() => console.log("promise8"))
// .then(() => console.log("promise9"))
// .then(() => console.log("promise10"))
// .then(() => console.log("promise11"))
// .then(() => console.log("promise12"))
// .then(() => console.log("promise13"));
function sleep(wait) {
return new Promise((resolve) => setTimeout(resolve, wait));
}
function asyncTask(name, awit) {
console.log(name);
return new Promise(async (resolve) => {
await sleep(awit);
resolve(name);
});
}
const limit = Promise.limit(1);
(async () => {
const res = await Promise.all(
["name", "age", "other"].map((v, k) =>
limit(() => asyncTask(v, 2000 * (k + 1)))
)
);
console.log(res);
})();