返回
Promise实现分析,面试加薪必备技能
前端
2023-11-30 20:02:40
手写Promise实现是许多大厂面试中常见的考题,对广大程序员来说也是一项必备技能。要想掌握Promise的精髓,首先要了解官方Promise的用法。官方Promise的使用方式如下:
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
resolve('Hello, Promise!');
}, 2000);
});
promise.then((result) => {
console.log(result); // 输出: 'Hello, Promise!'
}).catch((error) => {
console.log(error);
});
在这段代码中,首先创建一个Promise实例,传入一个执行器函数,执行器函数接受两个参数:resolve和reject。resolve用于将Promise的状态从pending变为fulfilled,并传入一个值作为结果。reject用于将Promise的状态从pending变为rejected,并传入一个错误对象作为原因。
然后,使用then方法来处理Promise的结果。then方法接收两个回调函数,第一个回调函数用于处理fulfilled状态的Promise,第二个回调函数用于处理rejected状态的Promise。
现在,让我们从头开始实现自己的Promise。首先,定义一个Promise类:
class Promise {
constructor(executor) {
this.state = 'pending'; // 初始状态为pending
this.value = undefined; // 存储最终结果
this.reason = undefined; // 存储错误原因
this.onFulfilledCallbacks = []; // 存储fulfilled状态的回调函数
this.onRejectedCallbacks = []; // 存储rejected状态的回调函数
// 立即执行执行器函数
executor(this.resolve.bind(this), this.reject.bind(this));
}
// 将Promise的状态从pending变为fulfilled
resolve(value) {
if (this.state !== 'pending') {
return;
}
this.state = 'fulfilled';
this.value = value;
// 执行所有fulfilled状态的回调函数
this.onFulfilledCallbacks.forEach((callback) => {
callback(value);
});
}
// 将Promise的状态从pending变为rejected
reject(reason) {
if (this.state !== 'pending') {
return;
}
this.state = 'rejected';
this.reason = reason;
// 执行所有rejected状态的回调函数
this.onRejectedCallbacks.forEach((callback) => {
callback(reason);
});
}
// then方法
then(onFulfilled, onRejected) {
// 如果onFulfilled不是函数,则将其设置为一个默认函数,返回value
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;
// 如果onRejected不是函数,则将其设置为一个默认函数,抛出错误
onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; };
// 创建一个新的Promise实例
const newPromise = new Promise((resolve, reject) => {
// 将onFulfilled和onRejected回调函数添加到新的Promise实例中
this.onFulfilledCallbacks.push((value) => {
try {
const result = onFulfilled(value);
resolve(result);
} catch (error) {
reject(error);
}
});
this.onRejectedCallbacks.push((reason) => {
try {
const result = onRejected(reason);
resolve(result);
} catch (error) {
reject(error);
}
});
});
// 返回新的Promise实例
return newPromise;
}
}
现在,我们已经实现了自己的Promise类。我们可以像使用官方Promise一样使用它。下面是一个示例:
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
resolve('Hello, Promise!');
}, 2000);
});
promise.then((result) => {
console.log(result); // 输出: 'Hello, Promise!'
}).catch((error) => {
console.log(error);
});
通过这个例子,我们了解了Promise的实现原理和使用方式。掌握Promise的精髓,可以帮助我们更好地理解异步编程,提升JavaScript开发能力。