跳到主要内容

实现一个Promise?

可以通过手动实现 Promise 的基本功能,来了解 Promise 的工作原理。以下是一个简单的不使用第三方库的 Promise 实现示例:

function CustomPromise(executor) {
// 初始化 Promise 的状态为 pending
this.status = "pending";
// 初始化 Promise 的值
this.value = undefined;
// 初始化 Promise 的回调函数队列
this.callbacks = [];

// 定义 resolve 函数,用于将 Promise 的状态从 pending 变为 fulfilled,并执行后续的操作
const resolve = (value) => {
if (this.status === "pending") {
this.status = "fulfilled";
this.value = value;
this.callbacks.forEach((callback) => callback.onFulfilled(value));
}
};

// 定义 reject 函数,用于将 Promise 的状态从 pending 变为 rejected,并执行后续的操作
const reject = (reason) => {
if (this.status === "pending") {
this.status = "rejected";
this.value = reason;
this.callbacks.forEach((callback) => callback.onRejected(reason));
}
};

// 执行 executor 函数,并传入 resolve 和 reject 函数作为参数
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}

// 定义 then 方法,用于注册 Promise 的回调函数
CustomPromise.prototype.then = function (onFulfilled, onRejected) {
// 创建一个新的 Promise 实例
return new CustomPromise((resolve, reject) => {
// 将回调函数包装成一个对象,以便后续处理
const callback = {
onFulfilled: (value) => {
try {
if (typeof onFulfilled === "function") {
const result = onFulfilled(value);
if (result instanceof CustomPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} else {
resolve(value);
}
} catch (error) {
reject(error);
}
},
onRejected: (reason) => {
try {
if (typeof onRejected === "function") {
const result = onRejected(reason);
if (result instanceof CustomPromise) {
result.then(resolve, reject);
} else {
reject(result);
}
} else {
reject(reason);
}
} catch (error) {
reject(error);
}
},
};

// 根据 Promise 的状态,执行回调函数或者将回调函数加入队列
if (this.status === "fulfilled") {
setTimeout(() => {
callback.onFulfilled(this.value);
});
} else if (this.status === "rejected") {
setTimeout(() => {
callback.onRejected(this.value);
});
} else {
this.callbacks.push(callback);
}
});
};

// 定义 catch 方法,用于捕获 Promise 的错误
CustomPromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};

// 测试 Promise
const promise = new CustomPromise((resolve, reject) => {
setTimeout(() => {
resolve("Success");
// reject('Error');
}, 1000);
});

promise
.then(
(value) => {
console.log("Resolved:", value);
return "New Value";
},
(reason) => {
console.log("Rejected:", reason);
throw new Error("New Error");
}
)
.then(
(value) => {
console.log("Resolved:", value);
},
(reason) => {
console.log("Rejected:", reason);
}
)
.catch((error) => {
console.log("Caught:", error);
});

这个简单的实现演示了 Promise 的基本功能,包括创建 Promise 实例、注册回调函数、处理异步操作、链式调用等。虽然这只是一个简单的示例,但它可以帮助理解 Promise 的工作原理以及如何手动实现一个基本的 Promise。