promise js 实现
Promise 实现原理
Promise 是 JavaScript 中处理异步操作的一种机制,其核心是通过状态管理、回调队列和链式调用来实现异步流程控制。以下是实现一个简易 Promise 的关键步骤:
基本结构
Promise 包含三种状态:pending、fulfilled 和 rejected。初始状态为 pending,最终会转变为 fulfilled 或 rejected。
class MyPromise {
constructor(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 方法接收两个回调函数 onFulfilled 和 onRejected,并返回一个新的 Promise 以实现链式调用。
then(onFulfilled, onRejected) {
const promise2 = new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
} else if (this.state === 'rejected') {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
} else {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
}
});
return promise2;
}
resolvePromise 函数
处理 then 方法返回的值,确保符合 Promise 规范(如处理嵌套 Promise 或 thenable 对象)。
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected'));
}
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 (e) {
if (called) return;
called = true;
reject(e);
}
} else {
resolve(x);
}
}
其他方法扩展
实现 catch、finally 和静态方法(如 Promise.resolve、Promise.all)。
catch(onRejected) {
return this.then(null, onRejected);
}
finally(callback) {
return this.then(
value => MyPromise.resolve(callback()).then(() => value),
reason => MyPromise.resolve(callback()).then(() => { throw reason; })
);
}
static resolve(value) {
return new MyPromise(resolve => resolve(value));
}
static reject(reason) {
return new MyPromise((_, reject) => reject(reason));
}
static all(promises) {
return new MyPromise((resolve, reject) => {
const results = [];
let count = 0;
promises.forEach((p, i) => {
p.then(
value => {
results[i] = value;
count++;
if (count === promises.length) resolve(results);
},
reject
);
});
});
}
注意事项
- 异步执行:
then的回调需要通过setTimeout或微任务队列(如queueMicrotask)异步执行,确保执行顺序符合规范。 - 错误处理:构造函数和
then方法中的错误需通过reject捕获。 - 链式调用:每次调用
then返回一个新的 Promise,避免状态污染。
以上实现简化了部分边界情况(如中止 Promise 链),但覆盖了核心功能。实际应用中建议直接使用原生 Promise 或成熟的库(如 Bluebird)。







