Promise 是一种用于处理异步操作的 JavaScript 对象,它可以将异步操作转换为同步操作,从而更加方便地进行错误处理和代码组织。Promise 的原理是基于状态机和回调函数。
Promise 有三种状态:pending(等待中)、fulfilled(已完成)和rejected(已拒绝)。当 Promise 被创建时,它的状态为 pending。当异步操作完成时,Promise 的状态会变为 fulfilled,并且会执行对应的成功回调函数。如果异步操作失败,则 Promise 的状态会变为 rejected,并且会执行对应的失败回调函数。
手动实现一个简单的 Promise:
```javascript
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => callback(this.value));
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach((callback) => callback(this.reason));
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
const promise2 = new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
}
if (this.state === 'rejected') {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
}
if (this.state === 'pending') {
this.onF