基本實(shí)現(xiàn)new Promise 和 then /catch方法
class Promise {
constructor(excutorCallback) {
this.status = 'pending' //new Primise 時(shí)為進(jìn)行中
this.value = undefined //resolve/reject的初始值(參數(shù))
this.fulfilledAry = [] //成功之后要做的事
this.rejectedAry = [] //失敗之后要做的事
let resolveFn = result => {
let timer = setTimeout(() => {
clearTimeout(timer)
if (this.status !== 'pending') return
this.status = 'fulfilled'
this.value = result
this.fulfilledAry.forEach(item => {
item(this.value)
})
}, 0)
}
let rejectFn = reason => {
let timer = setTimeout(() => {
clearTimeout(timer)
if (this.status !== 'pending') return
this.status = 'rejected'
this.value = reason
this.rejectedAry.forEach(item => {
item(this.value)
})
}, 0)
}
//實(shí)例化時(shí)異常捕獲
try {
excutorCallback(resolveFn, rejectFn)
} catch (err) {
//異常按rejected狀態(tài)處理
rejectFn(err)
}
}
//原型上加方法
then (fulfilledCallback, rejectedCallback) {
//then的參數(shù)不傳的情況 給它一個(gè)函數(shù)以承接數(shù)據(jù) 在后面的then里面就可以拿到了
typeof fulfilledCallback !== 'function' ? fulfilledCallback = result => result : null
typeof rejectedCallback !== 'function' ? rejectedCallback = reason => {
throw new Error(reason.message)
} : null
//鏈?zhǔn)讲僮鞣祷匾粋€(gè)新的Promise實(shí)例
return new Promise((resolve, reject) => {
this.fulfilledAry.push(() => {
try {
let x = fulfilledCallback(this.value)
x instanceof Promise ? x.then(resolve, reject) : resolve(x)
} catch (err) {
reject(err)
}
})
this.rejectedAry.push(() => {
try {
let x = rejectedCallback(this.value)
x instanceof Promise ? x.then(resolve, reject) : resolve(x)
} catch (err) {
reject(err)
}
})
})
}
//原型上添加catch方法
catch (rejectedCallback) {
return this.then(null, rejectedCallback)
}
}
module.exports = Promise
- test.js測(cè)試 調(diào)用手寫的Promise函數(shù)
const Promise = require('./Promise')
new Promise((resolve, reject) => {
// throw new Error('wrong')
resolve(100)
reject(-100)
}).then((result) => {
console.log(result);
console.log('成功')
}, (reason) => {
console.log(reason)
console.log('失敗')
})
console.log('同步方法');
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者