手写一个 Promise

手写一个 Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Promise = new Promise((resolve, reject) => {
if (/*操作成功*/) {
resolve(value);
} else {
reject(error);
}
});
Promise.then(
function (value) {
// success
},
function (value) {
// failure
}
);

使用 class 手写一个 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
//创建一个 Promise 的类
class Promise {
constructor(executer) {
//构造函数 constructor 里面是个执行器
this.status = "pending"; //默认的状态 pending
this.value = undefined; //成功的值默认 undefined
this.reason = undefined; //失败的值默认 undefined
//状态只有在 pending 时候才能改变
let resolveFn = value => {
//判断只有等待时才能 resolve 成功
if (this.status == pending) {
this.status = "resolve";
this.value = value;
}
};
//判断只有等待时才能 reject 失败
let rejectFn = reason => {
if (this.status == pending) {
this.status = "reject";
this.reason = reason;
}
};
try {
//把 resolve 和 reject 两个函数传给执行器 executer
executer(resolve, reject);
} catch (e) {
reject(e); //失败的话进 catch
}
}
then(onFufilled, onReject) {
//如果状态成功调用 onFufilled
if ((this.status = "resolve")) {
onFufilled(this.value);
}
//如果状态失败调用 onReject
if ((this.status = "reject")) {
onReject(this.reason);
}
}
}