class myPromise {
resolve;
reject;
// 构造函数 CustomPromise(executor):在构造函数中初始化 Promise 的状态为 pending,并接受一个执行器函数 executor,
// 该函数包含两个参数 resolve 和 reject,用于改变 Promise 的状态和传递结果或错误。
constructor(excuctor) {
this.status = "pending";
this.value = undefined;
this.error = undefined;
this.onResolveCallbacks = [];
this.onRejectCallbacks = [];
// resolve(value) 和 reject(error) 方法:分别用于将 Promise 状态改变为 fulfilled 和 rejected,并触发相应的回调函数。
const resolve = value => {
if (this.status === "pending") {
this.status = "fulfilled";
this.value = value;
this.onResolveCallbacks.forEach(callback => callback(this.value))
}
}
const reject = error => {
if (this.status === "pending") {
this.status = "rejected";
this.error = error;
this.onRejectCallbacks.forEach(callback => callback(this.error))
}
}
try {
excuctor(resolve, reject);
} catch (error) {
reject(error);
}
}
// then(onFulfilled, onRejected) 方法:用于注册成功和失败的回调函数,并返回一个新的 Promise 对象。
// 根据当前 Promise 的状态,分别处理 fulfilled 和 rejected 的情况,异步执行回调函数并根据返回值决定新 Promise 的状态和结果。
then(onFulfilled, onRejected){
return new myPromise((resolve, reject)=>{
const handleCallback = (callback, value, resolve, reject)=> {
try {
const result = callback(value);
if(result instanceof myPromise ){
result.then(resolve, reject)
}else{
resolve(result)
}
} catch (error) {
reject(error)
}
}
if(this.status === 'fulfilled'){
setTimeout(() => {
handleCallback(onFulfilled, this.value, resolve, reject)
}, 0);
}
if(this.status === 'rejected'){
setTimeout(() => {
handleCallback(onRejected, this.error, resolve, reject)
}, 0);
}
if(this.status === 'pending'){
this.onResolveCallbacks.push(() => {
setTimeout(() => {
handleCallback(onFulfilled, this.value, resolve, reject)
}, 0);
})
this.onRejectCallbacks.push(() => {
setTimeout(() => {
handleCallback(onRejected, this.error, resolve, reject)
}, 0);
})
}
})
}
// catch(onRejected) 方法:用于注册失败的回调函数,实际上是调用 then(null, onRejected)。
catch() {
return this.then(null, onRejected)
}
// 静态方法 resolve(value) 和 reject(error):分别返回一个已经 resolved 或 rejected 的 Promise 对象。
static resolve(value) {
return new myPromise((resolve, reject)=> {
resolve(value)
})
}
static reject(error) {
return new myPromise((resolve, reject) => {
reject(error)
})
}
// 静态方法 all(promises):接受一个 Promise 数组,并返回一个新的 Promise 对象,
// 当所有 Promise 都成功时,返回一个包含所有结果的数组;当任意一个 Promise 失败时,直接返回失败的 Promise。
static all(events) {
return new myPromise((resolve, reject) => {
const results = [];
let completeIndex = 0;
events.forEach((promise, index) => {
promise.then(res => {
results[index] = item;
completeIndex++;
if(completeIndex === results.length){
resolve(results)
}
}).catch(reject)
})
})
}
}
export default myPromise;
网友评论