当前位置:首页 > JavaScript

js promise 实现

2026-02-01 00:12:43JavaScript

Promise 的基本实现

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

实现 Promise 构造函数

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

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 或普通值。

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 的核心功能,但实际使用中还需考虑更多边界情况和性能优化。

js promise 实现

标签: jspromise
分享给朋友:

相关文章

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url,…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…