class MyPromise{
constructor(func){
this.status='pending';
this.value='';
this.resolveCallbacks=[];
this.rejectCallbacks=[];
const resolve=(value)=>{
if(this.status==='pending'){
this.status='fulfilled'
this.value = value;
this.resolveCallbacks.forEach(callback=>callback(this.value))
}
}
const reject=(error)=>{
if(this.status==='pending'){
this.status='rejected'
this.value = error;
this.rejectCallbacks.forEach(callback=>callback(this.value))
}
}
try{
func(resolve,reject)
}catch(error){
reject(error)
}
}
then(onResolve,onReject){
if(this.status==='fulfilled'){
onResolve(this.value)
}else if(this.status==='rejected'){
onReject(this.value)
}else{
this.resolveCallbacks.push(onResolve)
this.rejectCallbacks.push(onReject)
}
}
}
const promise = new MyPromise((resolve, reject) => {
// 异步操作,比如请求数据
setTimeout(() => {
resolve('成功');
// 或者 reject('失败');
}, 1000);
});
promise.then(
(value) => {
console.log('成功:', value);
},
(reason) => {
console.log('失败:', reason);
}
);
console