//定义三种状态
const success = 'success'
const pending = 'pending'
const fail = 'fail'
//定义用来实现的类
class Promise {
//定义构造器用来初始化变量或方法
constructor(execute) {
//初始化状态
this.status = pending
//初始化值
this.value = ''
//初始化成功回调数组
this.onsuccessCallback = []
//初始化成功回调数组
this.onfailCallback = []
//初始化失败原因
this.reason = ''
const resolve = (result) => {
if (this.status == 'pending') {
//改变状态
this.status = success
//赋值
this.value = result
//遍历并注册成功回调
this.onsuccessCallback.forEach(fn => { fn() })
}
}
const reject = (reason) => {
if (this.status == 'pending') {
//改变状态
this.status = fail
//赋值
this.reason = reason
//遍历并注册失败回调并传入原因
this.onfailCallback.forEach(fn => { fn(this.reason) })
}
}
//执行execute
execute(resolve, reject)
}
//注册成功回调和失败回调以处理 Promise 的结果
then(onResolved, onRejected) {
const handle = (resolve, reject, callback) => {
setTimeout(() => {
try {
const result = callback(this.value)
if (result instanceof Promise) {
result.then(resolve, reject)
} else {
resolve(result)
}
} catch (error) {
reject(error)
}
})
}
//返回一个新的 Promise,这使得可以创建 Promise 链。
//如果成功或失败回调返回的是一个 Promise,我们等待该 Promise 解决,并根据其状态触发新的 Promise。
return new Promise((resolve, reject) => {
if (this.status == 'success') {
handle(resolve, reject, onResolved)
}
if (this.status == 'fail') {
handle(resolve, reject, onRejected)
}
//处理异步
if (this.status == 'pending') {
this.onsuccessCallback.push((value) => {
handle(resolve, reject, onResolved);
});
this.onfailCallback.push((reason) => {
handle(resolve, reject, onRejected);
});
}
})
}
catch(onRejected) {
return this.then(null, onRejected)
}
finally(onFinally) {
return this.then(
(value) => {
onFinally();
return value;
},
(reason) => {
onFinally();
throw reason;
}
);
}
}
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('msg : hello' + '\n')
}, 1000)
})
promise.then(result => {
console.log('success' + '\n', result);
}, reject => {
throw new Error(reject)
}).catch((error) => {
console.log('error', error);
}).finally(() => {
console.log('Finally executed');
})
教你手写Promise
最新推荐文章于 2024-07-26 20:46:33 发布