-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathpromise.js
More file actions
40 lines (34 loc) · 697 Bytes
/
Copy pathpromise.js
File metadata and controls
40 lines (34 loc) · 697 Bytes
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
const PENDING = Symbol();
const REJECTED = Symbol();
const FULLFILLED = Symbol();
const MyPromise = function(fn) {
this.state = PENDING;
this.value = '';
const resolve = (value) => {
this.state = FULLFILLED;
this.value = value;
}
const reject = (error) => {
this.state = REJECTED;
this.value = error;
}
this.then = (onFullFill, onReject) => {
if (this.state == FULLFILLED) {
onFullFill(this.value);
} else {
onReject(this.value);
}
}
try {
fn(resolve, reject);
} catch(error) {
reject(error);
}
}
// test
let p = new MyPromise((resolve, reject) => {
resolve('hello');
})
p.then(res => {
console.log(res); // hello
})