-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
46 lines (37 loc) · 1.14 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
const PromiseTest = (fn) => {
let res = {}
fn((value) => {
res['value'] = value;
}, (err) => {
res['error'] = err;
})
return {getValue: () => res['value'], getError: () => res['error']}
}
const defer = (res) => (rej) => (callback) => (error) => (p) => {
if (p.getValue()) {
res(callback(p.getValue()))
} else if (p.getError()) {
error ? rej(error(p.getError())): rej(p.getError());
} else {
setTimeout(() => defer(res)(rej)(callback)(error)(p), 100);
}
}
const then = (p) => (callback, error) => {
return PromiseTest((res, rej) => {
if (p.getValue()) {
res(callback(p.getValue()))
} else if (p.getError()) {
error ? rej(error(p.getError())): rej(p.getError());
} else {
setTimeout(() => defer(res)(rej)(callback)(error)(p), 100);
}
})
}
const data = PromiseTest((res, rej) => {
console.log('execute')
res(1)
setTimeout(() => res(1), 100);
});
then(data)(e => console.log(e))
then(data)(e => console.log(e))
then(then(data)(e => e * 4, e => "test"))(e => console.log(e), e => console.log("Error " + e))