<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>kk</h2>
<script type="text/javascript">
// es6的写法
class MPromise {
// let state = 0;
constructor(executor) {
// executor functio立即执行函数,执行器函数
this.executor = executor;
this.state = 0;
this.result = null;
this.dealAsyncFunc();
this.then.bind(this)
this.autodeal = null;
this.callbacks = []
}
resolve(value) {
console.log(this)
this.state = 1;
// console.log(value)
this.result = value;
if (this.autodeal != null) {
this.autodeal(...this.callbacks);
}
}
reject(reason) {
this.state = 2;
// console.log(reason)
this.result = reason;
if (this.autodeal != null) {
this.autodeal(...this.callbacks);
}
}
dealAsyncFunc() {
try {
this.executor(this.resolve.bind(this), this.reject.bind(this));
} catch (err) {
this.reject(err)
}
}
// 同步执行函数!
then(cb1, cb2) {
this.callbacks.push(cb1);
this.callbacks.push(cb2);
// 根据状态 进行处理操作
if (this.state === 1) {
console.log(this.result)
cb1(this.result)
} else if (this.state === 2) {
cb2(this.result)
}
// 如果还是等待状态,则咋办呢?
// 如果还是等待状态,这个时候我们需要继续让它处理呗!
// 处于等待状态我们就不调用了,让类自己条用
this.autodeal = this.then;
}
}
window.onload = function () {
const p = new MPromise((resolve, reject) => {
setTimeout(() => {
resolve("java")
})
})
p.then((value) => {
console.log(value)
}, null)
}
</script>
</body>
</html>
代码有可能很low 但是确实实现了简单版本的promise
中间涉及了,回调函数的使用,this 指针的绑定处理,最重要的是同步和异步的处理
有两种情况, 1 异步先执行完毕,此时state 已经不是 0,pending状态,这个时候再执行then 可以很开心的返回结果
2, 异步没有执行完, 开始执行 then 方法,此时我们就不主动调用回调函数了,将回调函数保存起来,
在类的resolve reject 函数中,添加个钩子函数,让类实例自己调用 , 啥时,异步执行完毕,啥时候,调用钩子函数
______________________________
行,这篇就写到这,复习下promise