function Promise(fn){
this.value = null
this.state = 'PENDING'
this.deffered = []
fn.call(this, this.resolve.bind(this), this.reject.bind(this))
}
Promise.prototype = {
constructor: Promise,
then: function(onfulfilled, onrejected){
var obj = {
onfulfilled: onfulfilled,
onrejected: onrejected
}
obj.promise = new this.constructor(function(){})
if(this.state == 'PENDING'){
this.deffered.push(obj)
}
return obj.promise
},
catch: function(onrejected){
this.then(undefined, onrejected)
},
resolve: function(data) {
this.value = data;
this.status = 'FULFILLED';
this.deffered.forEach(task =>this.handler(task))
},
reject: function(err){
this.value = err
this.status = 'REJECTED'
this.deffered.forEach(task =>this.handler(task))
},
handler: function(task){
var status = this.status
var p;
switch(status){
case "FULFILLED":
p = task.onfulfilled(this.value)
break
case "REJECTED": {
P = tash.onrejected(this.value)
break
}
}
if(p && p.constructor == Promise){
p.deffered = task.promise.deffered
}
}
}
使用原生JS 实现 Promise基本功能
最新推荐文章于 2021-08-16 14:41:08 发布