class MyPromise{
constructor(fn){
this.queue = []
this.succ_res = null
this.fail_res = null
this.status = 'pending'
fn((...args) => {//resolve
this.succ_res = args
this.status = 'fulfilled'
this.queue.forEach((json) => {
json.fn1(...args)
})
},(...args) => {//reject
this.fail_res = args
this.status = 'rejected'
this.queue.forEach((json) => {
json.fn2(...args)
})
})
}
then(fn1,fn2){
if(this.status === 'fulfilled'){
fn1(...this.succ_res)
}else if(this.status === 'rejected'){
fn2(...this.fail_res)
}else{
this.queue.push({fn1,fn2})
}
}
}
MyPromise.all = function(arr){
let result = []
return new MyPromise(function(resolve,reject){
let i = 0
next()
function next(){
arr[i].then(function(res){
result.push(res)
i++
if(i == arr.length){
resolve(result)
}else{
next()
}
},reject)
}
})
}
let mp = new MyPromise(function(resolve,reject){
setTimeout(function(){
resolve(12)
},500)
})
mp.then(function (num){
console.log(num);
}, function (){
alert('错误')
})
let mp1 = new MyPromise(function(resolve,reject){
setTimeout(function(){
resolve(233)
},800)
})
MyPromise.all([mp,mp1]).then(function(arr){
let [res1,res2] = arr
console.log(res1)
console.log(res2)
},function(error){
console.log(error)
})
promise的简单实现
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 利用nodejs的event模块,可以实现一个最简单的Promise/Deferred框架: Promise De...
- 那一年我离婚了之(四)——我这么好的女人,你是不是瞎了!(中)“然后呢,然后呢?”嘉慧像极了一个急于听故事的孩子,...