forked from FrankFang/promise-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.ts
58 lines (54 loc) · 1.33 KB
/
promise.ts
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
class Promise2 {
state = "pending";
callbacks = [];
resolve(result) {
if (this.state !== "pending") return;
this.state = "fulfilled";
setTimeout(() => {
this.callbacks.forEach((handle) => {
typeof handle[0] === "function" && handle[0](result);
});
}, 0);
}
reject(reason) {
if (this.state !== "pending") return;
this.state = "rejected";
setTimeout(() => {
this.callbacks.forEach((handle) => {
typeof handle[1] === "function" && handle[1](reason);
});
}, 0);
}
constructor(fn) {
if (typeof fn === "function") {
fn(this.resolve, this.reject);
} else {
throw new Error("Not a function");
}
}
then(succeed?, fail?) {
const handle = [];
if (typeof succeed === "function") {
handle[0] = succeed;
}
if (typeof fail === "function") {
handle[1] = fail;
}
this.callbacks.push(handle);
}
}
export default Promise2;
function nextTick(fn) {
if (process !== undefined && typeof process.nextTick === "function") {
return process.nextTick(fn);
} else {
var counter = 1;
var observer = new MutationObserver(fn);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true,
});
counter = counter + 1;
textNode.data = String(counter);
}
}