手写原理 | 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
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

function myPromise(fn) {
// 保存初始的状态
const self = this;

// 定义初始的状态为pending
this.state = PENDING;

// 用于保存resolve reject传入的值
this.value = [];
// 用于保存resolve reject的回调函数
this.resolveCallbacks = [];
this.rejectCallbacks = [];

// 状态转变为resolve的操作
function resolve(value) {
// 判断传入元素是否为 Promise 值,如果是,则状态改变必须等待前一个状态改变后再进行改变
if (value instanceof myPromise) {
return value.then(resolve, reject);
}

// 保证代码的执行顺序为本轮事件循环的末尾
setTimeout(() => {
if (this.state === PENDING) {
this.state = FULFILLED;
this.value = value;
resolveCallbacks.forEach(callback=>callback(value));
}
}, 0);
}

// 状态转变为reject的操作
function reject(reason) {
setTimeout(() => {
if (this.state === PENDING) {
this.state = REJECTED;
this.value = reason;
resolveCallbacks.forEach(callback=>callback(reason));
}
}, 0);
}

// 把两个函数传入fn中
try{
fn(resolve, reject);
} catch (err) {
reject(err);
}
}