<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script>
class PromiseA {
constructor(executor) {
this.state = 'pending' //初始化state为等待装态
this.value = undefined //记录成功的状态值 将来的 .then使用
this.reason = undefined //记录失败的状态值 将来的 .catch使用
this.onResolvedCallback=[]//存放当成功时,需要执行的函数
this.onRejectedCallback=[]//存放当失败时,需要执行的函数
let resolve = (value) => {
//只有我们的pending状态能被改变其他不能
if (this.state == 'pending') {
// console.log('将状态改成成功,记录成功的信息');
this.state = 'fulfilled' //更新装态
this.value = value
//立刻调用成功的数组函数
this.onResolvedCallback.forEach(fn=>fn())
}
}
let reject = (reason) => {
if (this.state == 'pending') {
// console.log('将状态改成失败,记录失败的信息');
this.state = 'rejected' //更新装态
this.reason = reason
//立刻调用失败的数组函数
this.onRejectedCallback(fn=>fn())
}
}
//如果执行executor报错,直接reject
try{
executor(resolve, reject)
}catch(err){
reject(err)
}
}
then(onFulFilled,onRejected){
//onFulFilled 如果成功了,应该调用
if(this.state=='fulfilled'){
onFulFilled(this.value)
}
//onRejected 如果失败了,应该调用
if(this.state=='rejected'){
onRejected(this.reason)
}
//当我们的状态为pending的时候
if(this.state==='pending'){
//将成功的时候要干的事,存起来
this.onResolvedCallback.push(()=>{
onFulFilled(this.value)
})
//将失败要的时候要干的事,存起来
this.onRejectedCallback.push(()=>{
onFulFilled(this.reason)
})
}
}
}
//promiseA+ executor
const p = new PromiseA((resolve, reject) => {
setTimeout(()=>{
resolve(200)
},1000)
})
//这里的回调在promise更新成fulfilled
//如果有异步,有可能不是立即满足条件,就应该等满足条件,再来执行这个函数
p.then(res=>{
console.log(res,'1');
})
p.then(res=>{
console.log(res,'2');
})
p.then(res=>{
console.log(res,'3');
})
//调用三次,then后,效果=>数组存了三个等待执行的函数
// 应该在resolve,一旦resolve执行,就调用成功数组的函数
// 应该在reject,一旦reject执行,就调用失败数组的函数
</script>
</html>
封装Promise
最新推荐文章于 2024-10-01 20:12:28 发布
该文章展示了如何使用JavaScript实现一个Promise对象,包括构造函数、状态管理(pending,fulfilled,rejected)、then方法处理成功与失败的回调,以及在异步操作完成后调用相应的回调函数。通过实例演示了Promise的用法,如setTimeout模拟异步操作。
摘要由CSDN通过智能技术生成