-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path重写promise.1.html
79 lines (63 loc) · 2.44 KB
/
重写promise.1.html
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
75
76
77
78
79
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<meta name='viewport' content='width=device-width' />
<!--<script type="text/javascript" src='http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>-->
<!--<script type="text/javascript" src=' http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js'></script>-->
<!-- <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.2.0/css/bootstrap.min.css"> -->
<title>Document</title>
</head>
<body>
<h2>重写promise</h2>
<script>
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn) {
console.log('enter..')
var $this = this;
this.state = PENDING;
this.value = null;
this.resolvedCallbacks = [];
this.rejectedCallbacks = [];
fn(resolve)
function resolve(value) { //resolve函数执行后更改state为RESOLVED
if ($this.state == PENDING) {
$this.state = RESOLVED;
$this.value = value;
$this.resolvedCallbacks.forEach(cb => cb(value));
}
}
}
//resolve函数执行后更改state为RESOLVED
MyPromise.prototype = {
then: function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
if (this.state === PENDING) {
this.resolvedCallbacks.push(onFulfilled);
this.rejectedCallbacks.push(onRejected);
}
if (this.state === RESOLVED) {
onFulfilled(this.value);
}
if (this.state === REJECTED) {
onRejected(this.value);
}
}
}
function getList() {
return new MyPromise(resolve => {
setTimeout(() => {
resolve([1, 2, 3, 4]);
}, 10000)
})
}
getList().then(res => console.log(res, 'result'));
</script>
</body>
</html>