Skip to content

参考 [[202407021110-理解 Promise]] 中。

js
class SimplePromsie {
	constructor(executor) {
		this.state = "pending";
		this.value = undefined;
		this.error = undefined;
		this.onResolveCallbacks = [];
		this.onRejectCallbacks = [];

		const resolve = (value) => {
			if (this.state === "pending") {
				this.state = "fulfilled";
				this.value = value;
				// 执行回调函数
				this.onResolveCallbacks.forEach((callback) =>
					callback(this.value)
				);
			}
		};

		const reject = (error) => {
			if (this.state === "pending") {
				this.state = "rejected";
				this.error = error;
				// 执行回调函数
				this.onRejectCallbacks.forEach((callback) => {
					callback(this.error);
				});
			}
		};

		try {
			executor(resolve, reject); // 创建实例时立即执行
		} catch (error) {
			reject(error);
		}
	}
	
	// 注册处理成功和处理失败的回调函数
	then(onFulfilled, onRejected) {
		if (this.state === "fulfilled") {
			onFulfilled(this.value);
		} else if (this.state === "rejected") {
			onRejected(this.error);
		} else if (this.state === "pending") {
			this.onResolveCallbacks.push(onFulfilled);
			this.onRejectCallbacks.push(onRejected);
		}
		return this;
	}
}