-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplePromise.js
64 lines (54 loc) · 1.13 KB
/
simplePromise.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
/*
Build a Promise from scratch
*/
class SimplePromise {
constructor(callback) {
this.promiseChain = [];
this.handleError = () => {};
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
callback(this.onResolve, this.onReject);
}
then(success) {
this.promiseChain.push(success);
return this;
}
catch(error) {
this.handleError = error;
return this;
}
onResolve(value) {
let storedValue = value;
try {
this.promiseChain.forEach((next) => {
storedValue = next(value);
});
} catch (error) {
this.promiseChain = [];
this.onReject(error);
}
}
onReject(error) {
this.handleError(error);
}
}
let promise = new SimplePromise((resolver, reject) => {
setTimeout(() => {
const rand = Math.ceil(Math.random(1 * 1 + 6) * 6);
if (rand > 2) {
resolver("Success");
} else {
reject("Error");
}
}, 1000);
});
promise
.then(function (response) {
return response;
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});