手写promise

手写一个简单的 Promise 实现可以帮助理解 Promise 的基本原理。以下是一个基本的 Promise 实现,包括 resolverejectthen 方法。

1. 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
64
class MyPromise {
constructor(executor) {
this.state = 'pending'; // 初始状态
this.value = undefined; // 成功的值
this.reason = undefined; // 失败的原因
this.onResolvedCallbacks = []; // 存放成功的回调
this.onRejectedCallbacks = []; // 存放失败的回调

const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onResolvedCallbacks.forEach(callback => callback(value));
}
};

const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};

// 执行传入的 executor 函数
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}

// then 方法
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const handleFulfilled = () => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
};

const handleRejected = () => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
};

if (this.state === 'fulfilled') {
handleFulfilled();
} else if (this.state === 'rejected') {
handleRejected();
} else {
this.onResolvedCallbacks.push(handleFulfilled);
this.onRejectedCallbacks.push(handleRejected);
}
});
}
}

2. 使用示例

以下是如何使用自定义的 MyPromise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功!');
}, 1000);
});

promise
.then(result => {
console.log(result); // 输出: 成功!
return '继续处理';
})
.then(result => {
console.log(result); // 输出: 继续处理
})
.catch(error => {
console.error(error);
});

3. 特点

  • 状态管理:Promise 的状态只能从 pending 变为 fulfilledrejected,并且一旦变更,不能再变更。
  • 回调管理:成功和失败的回调被存储在数组中,只有在状态变更时调用。
  • 链式调用then 方法返回新的 Promise,支持链式调用。

4. 总结

这个简单的 Promise 实现展示了 Promise 的核心机制。在实际项目中,可以考虑更全面的实现,比如支持链式调用的返回值、异常处理等。


手写promise
https://garlandqian.github.io/2024/09/24/Interview/js/手写promise/
作者
Garland Qian
发布于
2024年9月24日
许可协议