lisa的个人博客

慢慢理解世界,慢慢更新自己

0%

手写promise

promise实现

promise优化了回调函数的用法,让原本需要纵向一层一层嵌套的回调函数实现了横向的调用,也就是链式调用。(解决地狱回调问题)

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
// myPromise 接收一个函数作为参数,函数中有两个函数参数,分别为resolve、reject作为成功或者失败的函数
function myPromise(cb) {
this.state = 'pending'; // 定义初始状态
this.result = null;
// 在没有通过 new 关键字去实例化的之前,它的内部方法this是无绑定状态的,
// 如果不做绑定,那么这个方法的 this 会指向 undefined,所以需要使用bind重新绑定this指向
cb(this.resolve.bind(this), this.reject.bind(this));
};

myPromise.prototype.resolve = function(val) {
if (this.state === 'pending') {
this.state = 'fullfiled';
this.result = val;
};
};

myPromise.prototype.reject = function(val) {
if (this.state === 'pending') {
this.state = 'rejected';
this.result = val;
};
};

// then函数接受两个函数参数,作为成功回调和失败回调
myPromise.prototype.then = function(isResolved, isRejected) {
if (this.state === 'fullfiled') {
const res = isResolved(this.result);
if (res instanceof myPromise) {
return res;
};
return this;
} else if (this.state === 'rejected') {
const error = new TypeError(this.result);
const res = isRejected(error);
if (res instanceof myPromise && auguments[0]) {
return res;
}
return this;
}
};

// catch方法专门给reject使用的
myPromise.prototype.catch = function(isRejected) {
if (this.state === 'rejected') {
const error = new TypeError(this.result);
const res = isRejected(error);
if (res instanceof myPromise && auguments[0]) {
return res;
}
return this;
}
}

let promise = new myPromise((resolve, reject) => {
reject("哎呦出错了");
});

promise
.then((data) => {
console.log(data);
}, (data) => {
console.log(data);
})