-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaive-promise-implementation.js
74 lines (66 loc) · 1.39 KB
/
naive-promise-implementation.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
/**
* new PromiseMy((resolve, reject) => {
*
* // do some stuff
* resolve();
*
* })
* @param callback
*/
function PromiseMy(callback) {
this.state = 'pending';
this.resolved = null;
this.rejected = null;
this.listeners = [];
this.errorlisteners = [];
function resolve(value) {
this.state = 'fulfilled';
this.resolved = value;
this.listeners.forEach((thenable) => {
try {
const val = thenable(this.resolved);
if (val) {
this.resolved = val;
}
} catch (e) {
this.errorlisteners.forEach((errL) => {
const val = errL(e);
if (val) {
this.resolved = val;
}
});
}
});
}
function reject(value) {
this.state = 'rejected';
this.rejected = value;
}
const res = resolve.bind(this);
const rej = reject.bind(this);
process.nextTick(() => {
callback(res, rej);
});
}
PromiseMy.prototype.then = function (callback) {
this.listeners.push(callback);
return this;
};
PromiseMy.prototype.catch = function (callback) {
this.errorlisteners.push(callback);
return this;
};
const a = new PromiseMy((res, rej) => {
res(123);
});
a.then((a) => {
console.log(`hye ia ms ${a}`);
return 4;
})
.then((b) => {
console.log(`hye i am second ${b}`);
throw new Error('Errorooooo')
})
.catch((e) => {
console.log('error caught', e);
});