class Promise {
constructor(executorCallback) {
let _that = this;
// 成功执行之后的返回值
_that.value = '';
// 失败的原因
_that.reason = undefined;
// 默认的状态
_that.status = 'pending';
// 成功执行的函数
// 成功执行会返回执行成功后的结果
function resolve(value) {
if ( _that.status === 'pending') {
_that.status = 'fulfilled';
_that.value = value;
}
}
// 失败执行的函数
// 失败返回失败的原因
function reject(reason) {
if ( _that.status === 'pending') {
_that.reason = reason;
_that.status = 'rejected';
}
}
// 捕获异常
try {
executorCallback(resolve, reject);
} catch (error) {
reject(error)
}
}
// then 的成功、失败 回调
/*onfulfilled : 成功回调
onRejected : 失败回调
*/
then(onFulfilled, onRejected) {
if (_that.status === 'fulfilled') {
onFulfilled(_that.value);
}
if (_that.status === 'rejected') {
onRejected(_that.reason);
}
}
}
module.exports = Promise;
/*
* promise 初始化会立即执行
* resolve 表示成功执行的函数
* reject 表示失败执行的函数
*
* promise 三个状态
*
* pending: 初始状态,既不是成功,也不是失败状态。
fulfilled: 意味着操作成功完成。
rejected: 意味着操作失败。
*
*/
手写一个简单的Promise
最新推荐文章于 2024-08-13 15:18:24 发布