const Fulfilled = 'fulfilled'
const Rejected = 'rejected'
const Pending = 'pending'
const promiseError = val => `(in promise) ${val}`
function P(fn) {
this.state = Pending
this.value = undefined
this.onFulfilledCb = []
this.onRejectedCb = []
const resolve = val => {
if (this.state === Pending) {
this.state = Fulfilled
this.value = val
while (this.onFulfilledCb.length) {
const fulfiledFn = this.onFulfilledCb.shift()
fulfiledFn()
}
}
}
const reject = val => {
if (this.state === Pending) {
this.state = Rejected
this.value = val
// if (!this.onRejectedCb.length) {
// throw promiseError(val)
// }
while (this.onRejectedCb.length) {
const rejectedFn = this.onRejectedCb.shift()
rejectedFn()
}
}
}
fn(resolve, reject)
}
P.prototype.then = function(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : r => r
return new P((resolve, reject) => {
const fulfilledHandler = () => {
try {
resolve(onFulfilled(this.value))
} catch (e) {
reject(e)
}
}
const rejectedHandler = () => {
// if (typeof onRejected === 'function') {
try {
resolve(onRejected(this.value))
} catch (e) {
reject(e)
}
// } else {
// throw promiseError(this.value)
// }
}
if (this.state === Pending) {
this.onFulfilledCb.push(fulfilledHandler)
this.onRejectedCb.push(rejectedHandler)
}
if (this.state === Fulfilled) {
fulfilledHandler()
}
if (this.state === Rejected) {
rejectedHandler()
}
})
}
P.prototype.catch = function(callback) {
return this.then(undefined, callback)
}
P.prototype.finally = function (callback) {
return this.then(callback, undefined)
}
P.resolve = function(val) {
return new P(resolve => resolve(val))
}
P.reject = function(val) {
return new P((_, reject) => reject(val))
}
P.all = function(arr) {
return new P((resolve, reject) => {
const values = []
let count = 0
for (let [i, p] of arr.entries()) {
p.then(res => {
values[i] = res
count++
if (count === arr.length) {
resolve(values)
}
}, err => {
reject(err)
})
}
})
}
P.race = function(arr) {
return new P((resolve, reject) => {
for (let p of arr) {
p.then(res => {
resolve(res)
}, err => {
reject(err)
})
}
})
}
实现一个简单的promise
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 利用nodejs的event模块,可以实现一个最简单的Promise/Deferred框架: Promise De...