在JavaScript中,Promise
是一个代表异步操作可能完成或失败的对象。在较老的浏览器或环境中,可能不支持 Promise
。为了在这些环境中使用 Promise
,我们可以实现一个简单的 Promise
polyfill。
以下是一个基本的 Promise
polyfill 的实现:
(function() {// 检查是否已存在 Promiseif (typeof window.Promise !== "undefined") {return;}// Promise 状态const PENDING = "pending";const RESOLVED = "resolved";const REJECTED = "rejected";// Promise 构造函数function Promise(executor) {let self = this;self.status = PENDING;self.value = undefined;self.reason = undefined;self.onResolvedCallbacks = [];self.onRejectedCallbacks = [];function resolve(value) {if (self.status === PENDING) {self.status = RESOLVED;self.value = value;self.onResolvedCallbacks.forEach(fn => fn());}}function reject(reason) {if (self.status === PENDING) {self.status = REJECTED;self.reason = reason;self.onRejectedCallbacks.forEach(fn => fn());}}try {executor(resolve, reject);} catch (err) {reject(err);}}// then 方法Promise.prototype.then = function(onResolved, onRejected) {let self = this;return new Promise((resolve, reject) => {function handledResolve(value) {try {let result = onResolved(value);resolve(result);} catch (err) {reject(err);}}function handledReject(reason) {try {let result = onRejected(reason);resolve(result);} catch (err) {reject(err);}}switch (self.status) {case RESOLVED:handledResolve(self.value);break;case REJECTED:handledReject(self.reason);break;default:self.onResolvedCallbacks.push(() => {handledResolve(self.value);});self.onRejectedCallbacks.push(() => {handledReject(self.reason);});break;}});};// catch 方法Promise.prototype.catch = function(onRejected) {return this.then(undefined, onRejected);};// 将 Promise 暴露给全局对象window.Promise = Promise;
})();
这个简单的 polyfill 实现了 Promise
的基本功能,包括构造函数、then
方法和 catch
方法。它允许你在不支持原生 Promise
的环境中使用基于 Promise 的异步编程模式。请注意,这个 polyfill 可能不包含 Promise
的所有功能和优化,但它为理解 Promise
的基本原理提供了一个很好的起点。