手动实现promise
2019-08-06 本文已影响0人
想当一个大头兵
具体版本应该是通过setTimeout(f,0)来模拟pedding转化状态,下面是为了方便理解跟面试,写了个简略版本的。
function promise () {
this.status = 'pending' // 2.1
this.msg = '' // 存储value与reason
let process = arguments[0],
that = this
process (function () {
that.status = 'resolve'
that.msg = argument[0]
}, function () {
that.status = 'reject'
that.msg = argument[0]
})
return this
}
promise.prototype.then = function () {
if (this.status === 'resolve') {
arguments[0](this.msg)
} else if (this.status === 'reject' && arguments[1]) {
arguments[1](this.msg)
}
}
ƒ () {
if (this.status === 'resolve') {
arguments[0](this.msg)
} else if (this.status === 'reject' && arguments[1]) {
arguments[1](this.msg)
}
}