Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
手写一个符合Promises/A+规范的Promise_js深度探索_创想鸟

手写一个符合Promises/A+规范的Promise_js深度探索

答案:手写符合Promises/A+规范的Promise需实现状态机、then链式调用与resolvePromise递归解析;包含pending/fulfilled/rejected三种状态,通过resolve/reject函数改变状态,then方法返回新Promise并注册回调,利用queueMicrotask确保异步执行,resolvePromise处理返回值为Promise或thenable的情况,防止循环引用,同时实现catch、finally、resolve、reject等辅助方法。

手写一个符合promises/a+规范的promise_js深度探索

要手写一个符合 Promises/A+ 规范的 Promise,关键在于理解其核心机制:状态机、异步执行、then 方法的链式调用与穿透,以及 onFulfilled 和 onRejected 的回调调度。下面从零实现一个精简但完全符合规范的 Promise 类。

Promise 核心状态与基本结构

Promise 有三种状态:pending(等待)、fulfilled(成功)、rejected(失败)。一旦状态变更,就不能再改变。

const PENDING = 'pending';const FULFILLED = 'fulfilled';const REJECTED = 'rejected';function MyPromise(executor) {  this.state = PENDING;  this.value = undefined;  this.reason = undefined;  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,实现链式调用。它接收两个可选参数:onFulfilled 和 onRejected。

MyPromise.prototype.then = function(onFulfilled, onRejected) {  // 处理透传,支持 .then().then(value => ...)  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;  onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; };  const promise2 = new MyPromise((resolve, reject) => {    if (this.state === FULFILLED) {      queueMicrotask(() => {        try {          const x = onFulfilled(this.value);          resolvePromise(promise2, x, resolve, reject);        } catch (e) {          reject(e);        }      });    }    if (this.state === REJECTED) {      queueMicrotask(() => {        try {          const x = onRejected(this.reason);          resolvePromise(promise2, x, resolve, reject);        } catch (e) {          reject(e);        }      });    }    if (this.state === PENDING) {      this.onFulfilledCallbacks.push(() => {        queueMicrotask(() => {          try {            const x = onFulfilled(this.value);            resolvePromise(promise2, x, resolve, reject);          } catch (e) {            reject(e);          }        });      });      this.onRejectedCallbacks.push(() => {        queueMicrotask(() => {          try {            const x = onRejected(this.reason);            resolvePromise(promise2, x, resolve, reject);          } catch (e) {            reject(e);          }        });      });    }  });  return promise2;};

处理 then 返回值:resolvePromise 函数

这个函数决定如何处理 onFulfilled/onRejected 的返回值 x。根据 Promises/A+ 规范,x 可能是普通值、Promise 或带有 then 方法的对象(即“thenable”)。

function resolvePromise(promise2, x, resolve, reject) {  if (promise2 === x) {    return reject(new TypeError('Chaining cycle detected for promise'));  }  let called = false;  if ((typeof x === 'object' && x !== null) || typeof x === 'function') {    let then;    try {      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 (e) {      if (called) return;      called = true;      reject(e);    }  } else {    resolve(x);  }}

补充常用方法:catch、finally、resolve、reject

这些是基于 then 的语法糖,增强使用体验。

MyPromise.prototype.catch = function(onRejected) {  return this.then(null, onRejected);};MyPromise.prototype.finally = function(callback) {  return this.then(    value => MyPromise.resolve(callback()).then(() => value),    reason => MyPromise.resolve(callback()).then(() => { throw reason; })  );};MyPromise.resolve = function(value) {  if (value instanceof MyPromise) return value;  return new MyPromise(resolve => resolve(value));};MyPromise.reject = function(reason) {  return new MyPromise((_, reject) => reject(reason));};

基本上就这些。这个实现覆盖了 Promises/A+ 的主要测试用例,包括异步回调、链式调用、错误捕获、循环引用检测等。关键是理解 resolvePromise 如何递归解析 thenable,以及 queueMicrotask 确保回调异步执行,模拟原生 microtask 队列行为。

以上就是手写一个符合Promises/A+规范的Promise_js深度探索的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1536243.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
js中有哪些书写位置
上一篇 2025年12月21日 03:06:59
JS DOM操作怎么实现_JS文档对象模型DOM操作详细指南
下一篇 2025年12月21日 03:07:11

相关推荐

发表回复

登录后才能评论
关注微信