手写promise简化版思路
文章目录
对手写思路进行说明
构造函数 constructor(executor)
- 接收一个执行器函数
executor,该函数接受两个参数:resolve和reject。 - 初始状态
status设为'pending',表示 Promise 尚未决议。 value属性用于存储 Promise 解决(fulfilled)或拒绝(rejected)时传递的值。onFulfilledCallbacks和onRejectedCallbacks用于存储.then或.catch中注册的回调函数,这些回调在 Promise 解决或拒绝时执行。
resolve 和 reject 函数
resolve(value)和reject(reason)函数改变 Promise 的状态并设置value,然后执行对应的回调函数列表。- 这两个函数检查当前状态是否为
'pending',以防止 Promise 状态被多次改变。 - 当
resolve被调用时,状态变为'fulfilled',并异步执行所有onFulfilledCallbacks中的函数。 - 当
reject被调用时,状态变为'rejected',并异步执行所有onRejectedCallbacks中的函数。
then(onFulfilled, onRejected)
then方法接收两个参数:onFulfilled和onRejected,它们分别是 Promise 解决或拒绝时的回调函数。- 提供默认函数以确保即使未传递这些函数,
then方法也能正常返回一个新的 Promise。 - 根据当前 Promise 的状态,决定立即执行回调还是将回调加入对应的回调列表。
- 返回一个新的
SimplePromise对象,允许链式调用。
链式调用和异步执行
then和catch方法通过返回新的SimplePromise实例来支持链式调用。- 异步执行回调是通过将回调函数包裹在
setTimeout中实现的,确保回调总是在函数执行栈清空后异步执行。
错误处理
- 在
executor执行或回调函数执行中捕获异常,并将异常作为拒绝的理由传递给reject函数。
catch(onRejected)
catch方法是then方法的语法糖,只处理拒绝的情况。
这个 SimplePromise 类实现了 then 和 catch,但没有实现 Promise 的全部功能,例如 Promise.all, Promise.race, Promise.resolve, Promise.reject 等静态方法。此外,这个实现也没有处理一些边缘情况,例如处理链式调用中返回自身的 Promise,或者处理 then 中返回另一个 Promise 的情况。这些都是在完整的、遵循 Promises/A+ 规范的实现中需要考虑的复杂性。
class SimplePromise {
constructor(executor) {
// 初始化状态为 'pending'
this.status = 'pending';
// value 用于保存成功或失败的返回值
this.value = null;
// 保存成功和失败的处理函数
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
// 成功处理函数
const resolve = (value) => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => callback(value));
}
};
// 失败处理函数
const reject = (reason) => {
if (this.status === 'pending') {
this.status = 'rejected';
this.value = reason;
this.onRejectedCallbacks.forEach((callback) => callback(reason));
}
};
// 立即执行executor,并传入resolve和reject
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
// 如果onFulfilled不是函数,提供一个默认函数,返回value
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;
// 如果onRejected不是函数,提供一个默认函数,抛出错误
onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; };
// 返回一个新的Promise
return new SimplePromise((resolve, reject) => {
// 如果状态已经确定为fulfilled,立即执行onFulfilled
if (this.status === 'fulfilled') {
setTimeout(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
});
}
// 如果状态已经确定为rejected,立即执行onRejected
if (this.status === 'rejected') {
setTimeout(() => {
try {
const result = onRejected(this.value);
reject(result);
} catch (error) {
reject(error);
}
});
}
// 如果状态仍然是pending,将onFulfilled和onRejected放入对应的处理数组中
if (this.status === 'pending') {
this.onFulfilledCallbacks.push((value) => {
try {
const result = onFulfilled(value);
resolve(result);
} catch (error) {
reject(error);
}
});
this.onRejectedCallbacks.push((reason) => {
try {
const result = onRejected(reason);
reject(result);
} catch (error) {
reject(error);
}
});
}
});
}
catch(onRejected) {
// catch是then的一个语法糖,只提供onRejected处理函数
return this.then(null, onRejected);
}
}
// 示例1:resolve
const promise1 = new SimplePromise((resolve, reject) => {
resolve('test resolve')
})
promise1.then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
// 示例2:rejected
const promise2 = new SimplePromise((resolve, reject) => {
reject('test reject')
})
promise2.then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
// 示例3 异步操作
const promise3 = new SimplePromise((resolve, reject) => {
setTimeout(() => {
resolve('test after timeout')
}, 1000);
})
promise3.then(res => {
console.log(res)
}).catch(err=>{
console.log(err)
})
// 示例4:异步调用
const promise4 = new SimplePromise((resolve, reject) => {
resolve(1)
})
promise4.then(res => {
console.log(res)
return res + 1
}).then(res => {
console.log(res)
return res + 1
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论