答案:文章实现了一个符合Promises/A+规范的简易Promise,包含三种状态(pending、fulfilled、rejected)、构造函数、then方法链式调用、resolvePromise解析逻辑及静态resolve/reject方法,通过queueMicrotask处理异步回调,支持Promise链式传递与错误捕获。

实现一个符合 Promises/A+ 规范的 Promise 并不是一件简单的事,但通过一步步拆解核心逻辑,我们可以手写一个基本符合规范的简易版本。下面是一个简化但关键流程正确的 Promise 实现,帮助你深入理解其工作机制。
根据 Promises/A+ 规范,Promise 有三种状态:
状态一旦从 pending 变为 fulfilled 或 rejected,就不能再改变。
我们从构造函数开始,接收一个执行器函数(executor),并初始化状态和值。
立即学习“Java免费学习笔记(深入)”;
function MyPromise(executor) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
// 存储 then 注册的成功和失败回调
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
// 执行所有成功的回调
this.onFulfilledCallbacks.forEach(fn => fn());
}
};
const reject = (reason) => {
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
// 执行所有失败的回调
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error); // 如果执行器出错,直接 reject
}
}
then 方法是 Promise 的核心,用于注册成功和失败的回调,并返回一个新的 Promise,支持链式调用。
MyPromise.prototype.then = function(onFulfilled, onRejected) {
// 处理回调可选的情况
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
// 返回一个新的 Promise
const promise2 = new MyPromise((resolve, reject) => {
if (this.status === 'fulfilled') {
queueMicrotask(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (this.status === 'rejected') {
queueMicrotask(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
// 如果还是 pending,先缓存回调函数
if (this.status === '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;
};
这个函数处理 x 的情况,判断它是否是 Promise,决定如何解析并 resolve 或 reject promise2。
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called = false; // 防止多次调用 resolve/reject
if (x != null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then;
if (typeof then === 'function') {
// 认为是 Promise 类型
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);
}
}
提供快捷方式创建已解决或已拒绝的 Promise。
MyPromise.resolve = function(value) {
return new MyPromise((resolve) => resolve(value));
};
MyPromise.reject = function(reason) {
return new MyPromise((resolve, reject) => reject(reason));
};
测试我们实现的 Promise:
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Hello');
}, 1000);
})
.then(value => {
console.log(value); // 1秒后输出 Hello
return value + ' World';
})
.then(value => {
console.log(value); // 输出 Hello World
});
基本上就这些。这个实现覆盖了 Promises/A+ 的核心机制:状态管理、异步任务队列(使用 queueMicrotask)、then 的链式调用和 resolvePromise 的递归解析。虽然省略了一些边界检查和更复杂的兼容逻辑,但它能帮助你理解 Promise 背后的运行原理。
以上就是手写一个符合Promises/A+规范的Promise_javascript进阶的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号