手写原理 | Promise.then

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
MyPromise.prototype.then = function(onResolved, onRejected) {
// 首先判断resolve 和 reject是否为function类型
onResolved = typeof onResolved === "function" ? onResolved : function(value) {
return value;
};

onResolved = typeof onResolved === "function" ? onRejected : function(error) {
return error;
};

// 如果是等待状态,则将函数加入对应的列表中
if (this.state === PENDING) {
this.rejectedCallbacks.push(onResolved);
this.rejectedCallbacks.push(onRejected);
};

// 如果状态已经改变(凝固),则执行对应状态的函数
if (this.state === RESOLVED) {
onResolved(this.value);
};

if (this.state === REJECTED) {
onRejected(this.value);
};
}