当前位置:首页 > JavaScript

js promise 实现

2026-02-01 00:12:43JavaScript

Promise 的基本实现

Promise 是 JavaScript 中用于处理异步操作的对象。以下是 Promise 的基本实现方式,包括状态管理、then 方法和异步支持。

实现 Promise 构造函数

Promise 构造函数接收一个执行器函数(executor),该函数包含 resolve 和 reject 两个参数。

js promise 实现

function Promise(executor) {
  this.state = 'pending'; // Promise 的初始状态
  this.value = undefined; // resolve 的值
  this.reason = undefined; // reject 的原因
  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 (error) {
    reject(error);
  }
}

实现 then 方法

then 方法用于注册 Promise 状态改变时的回调函数,支持链式调用。

Promise.prototype.then = function(onFulfilled, onRejected) {
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
  onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };

  const promise2 = new Promise((resolve, reject) => {
    if (this.state === 'fulfilled') {
      setTimeout(() => {
        try {
          const x = onFulfilled(this.value);
          resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      }, 0);
    } else if (this.state === 'rejected') {
      setTimeout(() => {
        try {
          const x = onRejected(this.reason);
          resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      }, 0);
    } else {
      this.onFulfilledCallbacks.push(() => {
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      });

      this.onRejectedCallbacks.push(() => {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      });
    }
  });

  return promise2;
};

实现 resolvePromise 函数

resolvePromise 用于处理 then 方法中返回的新 Promise 或普通值。

js promise 实现

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise'));
  }

  let called = false;
  if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
    try {
      const 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 (error) {
      if (called) return;
      called = true;
      reject(error);
    }
  } else {
    resolve(x);
  }
}

实现其他静态方法

Promise 还提供了一些静态方法,如 Promise.resolve、Promise.reject 和 Promise.all。

Promise.resolve = function(value) {
  return new Promise((resolve) => {
    resolve(value);
  });
};

Promise.reject = function(reason) {
  return new Promise((_, reject) => {
    reject(reason);
  });
};

Promise.all = function(promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let count = 0;

    promises.forEach((promise, index) => {
      Promise.resolve(promise).then(
        value => {
          results[index] = value;
          count++;
          if (count === promises.length) {
            resolve(results);
          }
        },
        reject
      );
    });
  });
};

使用示例

以下是如何使用自定义实现的 Promise。

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success');
  }, 1000);
});

p.then((value) => {
  console.log(value); // 输出: success
  return 'another value';
}).then((value) => {
  console.log(value); // 输出: another value
});

注意事项

  • 异步支持:通过 setTimeout 确保 then 方法中的回调函数异步执行。
  • 链式调用:then 方法返回一个新的 Promise,支持链式调用。
  • 错误处理:在执行器函数和 then 回调中捕获错误,并通过 reject 传递。

以上实现涵盖了 Promise 的核心功能,但实际使用中还需考虑更多边界情况和性能优化。

标签: jspromise
分享给朋友:

相关文章

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…