feat: 添加静态函数reslove和reject以及all
This commit is contained in:
parent
d8433e0682
commit
eee04539d8
@ -19,12 +19,14 @@ MyPromise.REJECT = 2
|
|||||||
|
|
||||||
|
|
||||||
MyPromise.resolve = function(res) {
|
MyPromise.resolve = function(res) {
|
||||||
|
if(this === MyPromise) return new MyPromise(resolve=>resolve(res)) // 如果是静态调用就返回一个确认的Promise
|
||||||
if(this.status === MyPromise.REJECT) return // Promise 的状态一旦确定就不能修改
|
if(this.status === MyPromise.REJECT) return // Promise 的状态一旦确定就不能修改
|
||||||
this.status = MyPromise.FULFILLED
|
this.status = MyPromise.FULFILLED
|
||||||
this.result = res
|
this.result = res
|
||||||
}
|
}
|
||||||
|
|
||||||
MyPromise.reject = function(err) {
|
MyPromise.reject = function(err) {
|
||||||
|
if(this === MyPromise) return new MyPromise((resolve,reject)=>reject(err)) // 如果是静态调用就返回一个拒绝的Promise
|
||||||
if(this.status === MyPromise.FULFILLED) return // Promise 的状态一旦确定就不能修改
|
if(this.status === MyPromise.FULFILLED) return // Promise 的状态一旦确定就不能修改
|
||||||
this.status = MyPromise.REJECT
|
this.status = MyPromise.REJECT
|
||||||
this.result = err
|
this.result = err
|
||||||
@ -50,3 +52,31 @@ MyPromise.prototype = {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 编写Promise.all([...Promies])静态方法
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @description 接受一个Promise的迭代对象,当全部的Promise兑现时,返回一个由兑现值组成的迭代对象
|
||||||
|
* 当为空的迭代对象时也会对象一个空的迭代对象 Promise.all([]).then(res=>{console.log(res)}) res = []
|
||||||
|
*/
|
||||||
|
MyPromise.all = function (ps) {
|
||||||
|
if(typeof ps[Symbol.iterator] !== 'function') throw new Error("传递一个内容为Promise实例的可迭代对象")
|
||||||
|
var n = ps.length
|
||||||
|
var rs = []
|
||||||
|
for(var i = 0; i < n; i++) {
|
||||||
|
(function(i){
|
||||||
|
ps[i].then(res=>{
|
||||||
|
rs[i] = res
|
||||||
|
}, err=>{
|
||||||
|
// all只要出现拒绝,就立马返回第一个拒绝的内容
|
||||||
|
this.status = MyPromise.REJECT;
|
||||||
|
this.result = err
|
||||||
|
})
|
||||||
|
}).call(this, i)
|
||||||
|
}
|
||||||
|
if (this.status === MyPromise.REJECT) return this
|
||||||
|
|
||||||
|
this.status = MyPromise.FULFILLED
|
||||||
|
this.result = rs
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user