手写一个简单的 Promise 实现可以帮助理解 Promise 的基本原理。以下是一个基本的 Promise 实现,包括 resolve
、reject
和 then
方法。
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)); } };
try { executor(resolve, reject); } catch (error) { reject(error); } }
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
变为 fulfilled
或 rejected
,并且一旦变更,不能再变更。
- 回调管理:成功和失败的回调被存储在数组中,只有在状态变更时调用。
- 链式调用:
then
方法返回新的 Promise,支持链式调用。
4. 总结
这个简单的 Promise 实现展示了 Promise 的核心机制。在实际项目中,可以考虑更全面的实现,比如支持链式调用的返回值、异常处理等。