返回
从手动实现 Promise 看「面试官问你对 Promise 的理解」
前端
2023-11-12 23:36:36
Promise 的基本原理
Promise 是一个异步编程的解决方案,它允许我们将异步操作的结果作为值传递给后续的操作。Promise 对象代表一个异步操作的结果,它有三种状态:pending(等待)、fulfilled(已完成)和 rejected(已拒绝)。
当一个 Promise 对象被创建时,它处于 pending 状态。当异步操作完成时,Promise 对象的状态会改变为 fulfilled 或 rejected。如果异步操作成功,则 Promise 对象的状态变为 fulfilled,并带有结果值。如果异步操作失败,则 Promise 对象的状态变为 rejected,并带有错误信息。
手动实现 Promise
我们可以手动实现一个 Promise 对象,以便更好地理解它的工作原理。以下是如何手动实现 Promise 对象的步骤:
- 定义一个 Promise 构造函数:
function Promise(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((callback) => {
callback(value);
});
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach((callback) => {
callback(reason);
});
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
- 定义
then
方法:
Promise.prototype.then = function (onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
}, 0);
} else if (this.state === 'rejected') {
setTimeout(() => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
}, 0);
} else {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
}, 0);
});
}
});
};
- 使用 Promise:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello, Promise!');
}, 1000);
});
promise.then((result) => {
console.log(result); // Hello, Promise!
});
面试官问你对 Promise 的理解
面试官问你对 Promise 的理解,可能是想考察你对 Promise 的基本原理的掌握程度。你应该能够解释 Promise 的基本概念,如状态、then
方法等。你还可以谈谈你对 Promise 的使用经验,以及你认为 Promise 的优点和缺点。
如果你能够手动实现一个 Promise 对象,那么你对 Promise 的理解一定是非常深刻的。这将给面试官留下深刻的印象,并增加你被录用的几率。