-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathpromise.js
57 lines (52 loc) · 1.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
class Promise {
constructor(callback) {
this.state = 'pending';
this.onFulfilledCallback = null;
this.onRejectedCallback = null;
const resolve = value => {
this.state = 'fulfilled';
this.value = value;
if (this.onFulfilledCallback !== null) {
this.onFulfilledCallback(value);
}
};
const reject = value => {
this.state = 'rejected';
this.value = value;
if (this.onRejectedCallback !== null) {
this.onRejectedCallback(value);
}
};
callback(resolve, reject);
}
then(callback) {
if (this.state === 'pending') {
this.onFulfilledCallback = callback;
}
if (this.state === 'fulfilled') {
callback(this.value);
}
return this;
}
catch(callback) {
if (this.state === 'pending') {
this.onRejectedCallback = callback;
}
if (this.state === 'rejected') {
callback(this.value);
}
return this;
}
getValue() {
return this.value;
}
}
function asyncResolve() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('resolved after 1s'), 1000);
});
}
asyncResolve().then(result => console.log(result));
asyncResolve()
.then(result => `next ${result}`)
.then(result => console.log(`should log "next result" but ${result} logged`));