<script>
function myPromise(excutor) {
let self = this
self.status = 'pending'
self.value = null
self.reason = null
self.onFulfilledCallbacks = []
self.onRejectedCallbacks = []
function resolve(value) {
console.log(this); //this 是window
if (self.status === 'pending') {
self.value = value
self.status = 'fulfiled'
self.onFulfilledCallbacks.forEach((item) => {
item(value)
})
}
}
function reject(reason) {
if (self.status === 'pending') {
self.reason = reason
self.status = 'rejected'
self.onRejectedCallbacks.forEach((item) => {
item(reason)
})
}
}
excutor(resolve, reject)
}
myPromise.prototype.then = function (
onFulfilled, onRejected
) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (data) {
resolve(data)
}
onRejected = typeof onRejected === 'function' ? onRejected : function (data) {
reject(data)
}
// onFulfilled()
console.log(this.status);
//若果是pending状态我就不执行,先存起来
if (this.status === 'pending') {
this.onFulfilledCallbacks.push(onFulfilled)
this.onRejectedCallbacks.push(onRejected)
}
// if (this.status === 'pending') {
// }
}
let demo = new myPromise((resolve, reject) => {
setTimeout(() => {
resolve(3)
}, 1);
// resolve(3)
}).then((res) => {
console.log(res, 0000);
console.log(1);
})
// function B() {
// function c() {
// console.log(1);
// }
// }
// B.prototype.test = function () {
// c()
// }
// let tao = new B()
// tao.test()
</script>
要点,因为是异步 。then()的时候 reslove的状态并没有改变
其实在时间线上,then()会比reslove() 先执行
所以在。then()判断是否为pending,若果是pending就挂起来,在reslove的时候再去取
reslove function 中的this是