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







