const PENDING = Symbol('pending')
const FULLFILLED = Symbol('fullfilled')
const REJECTED = Symbol('rejected')
class Promise {
constructor (fn) {
this.status = PENDING
this.value = undefined
this.resolveFunc = () => {
}
this.rejectFunc = () => {
}
fn.call(this, this.resolve.bind(this), this.reject.bind(this))
}
resolve (value) {
if (this.status == PENDING) {
this.status = FULLFILLED
this.value = value
this.resolveFunc(value)
}
}
reject (value) {
if (this.status == PENDING) {
this.status = REJECTED
this.value = value
this.rejectFunc(value)
}
}
then (resolveFunc, rejectFunc) {
return new Promise((resolve_next, reject_next) => {
const resolveFuncWrap = () => {
try {
let result = resolveFunc(this.value)
if (result && typeof result.then == 'function') {
result.then(resolve_next, reject_next)
} else {
resolve_next(result)
}
} catch (e) {
reject_next(e)
}
}
const rejectFuncWrap = () => {
let result = rejectFunc(this.value)
reject_next(result)
}
this.resolveFunc = resolveFuncWrap
this.rejectFunc = rejectFuncWrap
})
}
catch (errCallback) {
this.rejectFunc = errCallback
}
}
let hello = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hello')
}, 1000)
})
}
hello().then(res1 => {
console.log('res1: ', res1)
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('world')
})
})
}).then(res2 => {
console.log('res2:', res2)
// 测试出 error 情况
console.log('error:', hello.i.b)
}).catch(err => {
console.log('error: ', err)
})
网友评论