promise是用来解决两个问题的:
- 回调地狱,代码难以维护, 常常第一个的函数的输出是第二个函数的输入这种现象
- promise可以支持多个并发的请求,获取并发请求中的数据
- 这个promise可以解决异步的问题,本身不能说promise是异步的
实现代码
class mypromise {
constructor(exeutor) {
this.state = PENDING
//成功的存储
this.value = undefined
//失败的存储
this.reason = undefined
//存放成功时候的回调函数
this.ResolveCallbakc = []
//存放失败时候的回调函数
this.RejectCallback = []
//要把这个值保存起来 调用then的时候还需要使用
let resolve = (value) => {
if (this.state == PENDING) {
//定时器用于then先注册才去改变状态
setTimeout(()=>{
//存起来
console.log('成功的构造');
this.value = value
//改变状态
this.state = FULFILLED
//全执行
this.ResolveCallbakc.forEach(fn => fn()) //发布过程
})
}
}
let reject = (reason) => {
if (this.state == PENDING) {
setTimeout(()=>{
console.log('失败的构造');
//也存起来
this.reason = reason
this.state = REJECTED
this.RejectCallback.forEach(fn => fn())
})
}
}
//传入两个参数 给用户来改变状态
try {
exeutor(resolve, reject)
} catch (e) {
//当前有异常
reject(e)
}
}
then(onfulfilled, onrejected) {
if (this.state == FULFILLED) {
onfulfilled(this.value)
}
if (this.state == REJECTED) {
onrejected(this.reason)
}
if (this.state == PENDING) {
console.log('推入函数');
this.ResolveCallbakc.push(() => {
onfulfilled(this.value)
})
this.RejectCallback.push(() => {
onrejected(this.reason)
})
//链式调用
return this;
}
}
}
实例
let fanfan = new mypromise((resolve, reject) => {
console.log('?');
resolve('fanfan')
}).then(res => {
setTimeout(()=>{
console.log('time');
})
console.log(res);
}).then(res => {
console.log('?');
}).then(res=>{
console.log(res);
})
// 打印结果 可以看到先是then去注册完才去调用状态改变
//先微后宏
/**
?
promise2.html:78 推入函数
promise2.html:78 推入函数
promise2.html:78 推入函数
promise2.html:37 成功的构造
promise2.html:100 fanfan
promise2.html:103 ?
promise2.html:106 fanfan
promise2.html:98 time
*/