实现一个简单的Promise库,包括Promise的基本功能和异常处理机制。
实现简单的Promise库
1. 基本结构
首先,定义Promise的基本结构,包括三个状态:pending(初始状态)、fulfilled(已成功)和rejected(已失败)。并定义构造函数接受一个执行器(executor)回调函数,该函数接受两个参数:resolve和reject,分别用于改变Promise的状态。
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function SimplePromise(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(fn => fn());
}
};
const reject = reason => {
if (this.state === PENDING) {
this.state = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
2. 实现then方法
then方法用于注册成功和失败的回调函数,并返回一个新的Promise,以便支持链式调用。当Promise状态为fulfilled时,执行成功回调;当状态为rejected时,执行失败回调。如果回调函数抛出错误,新的Promise将变为rejected状态。
SimplePromise.prototype.then = function(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; };
let promise2;
if (this.state === FULFILLED) {
promise2 = new SimplePromise((resolve, reject) => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
} else if (this.state === REJECTED) {
promise2 = new SimplePromise((resolve, reject) => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
} else if (this.state === PENDING) {
promise2 = new SimplePromise((resolve, reject) => {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
});
}
return promise2;
};
3. 解决Promise A+规范中的x值问题
resolvePromise函数用于处理x值,确保遵循Promise A+规范。如果x是一个Promise,等待其状态改变;如果x是一个普通值,直接返回x。
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'));
}
let called;
if ((typeof x === 'object' && x !== null) || typeof x === 'function') {
try {
let then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else {
resolve(x);
}
}
4. 测试示例
const promise = new SimplePromise((resolve, reject) => {
setTimeout(() => {
resolve('Hello World!');
}, 1000);
});
promise.then(value => {
console.log(value); // Hello World!
return 'New Value';
}).then(value => {
console.log(value); // New Value
});
const promise2 = new SimplePromise((resolve, reject) => {
setTimeout(() => {
reject('Error!');
}, 1000);
});
promise2.then(null, reason => {
console.error(reason); // Error!
});
5. 异常处理
在then方法中,通过try...catch捕获回调函数执行期间可能出现的任何异常,并将这些异常传递给新的Promise的reject方法,确保错误能够正确地传递下去。
6. 总结
通过以上步骤,我们实现了一个简单的Promise库,包含了基本功能和异常处理机制。这个库能够支持链式调用,并且遵循Promise A+规范,确保在异步编程中的使用更加安全和可靠。