class newPromise {
constructor(fn) {
this.state = "pending"
this.value = null
this.resolveCallbacks = []
this.rejectCallbacks = []
this.resolve = res => {
if (this.state === "pending") {
setTimeout(() => {
this.state = "resolved"
this.value = res
this.resolveCallbacks.map(cb => cb(this.value))
}, 0)
}
}
this.reject = err => {
if (this.state === "pending") {
setTimeout(() => {
this.state = "rejected"
this.value = err
this.rejectCallbacks.map(cb => cb(this.value))
}, 0)
}
}
try {
fn(this.resolve, this.reject)
} catch (err) {
this.reject(err)
}
}
then(onResolve, onReject) {
console.log("調(diào)用then")
var promise2 = new newPromise((res, rej) => {
if (this.state === "pending") {
this.resolveCallbacks.push(val => {
try {
let data = onResolve(val)
res(data)
} catch (e) {
rej(e)
}
})
this.rejectCallbacks.push(val => {
try {
let data = onReject(val)
res(data)
} catch (e) {
rej(e)
}
})
}
if (this.state === "resolved") {
try {
let data = onResolve(val)
res(data)
} catch (e) {
rej(e)
}
}
if (this.state === "rejected") {
try {
let data = onReject(val)
res(data)
} catch (e) {
rej(e)
}
}
})
return promise2
}
resolvePromise(promise2, x, resolve, reject) {}
}
newPromise.resolve = function(x) {
return new newPromise((res, rej) => {
return res(x)
})
}
newPromise.reject = function(x) {
return new newPromise((res, rej) => {
return rej(x)
})
}
newPromise.all = function(arr) {
return new newPromise((res, rej) => {
var result = []
var step = 0
for (let i = 0; i < arr.length; i++) {
arr[i].then(val => {
result[i] = val
step++
if (step === arr.length) {
res(result)
}
}, rej)
}
})
}
newPromise.race = function(arr){
return new newPromise((res, rej) => {
for(let i = 0; i < arr.length; i++){
arr[i].then(val => {
res(val)
}, rej)
}
})
}
finally
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);
};
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。