手写Promise
let flag = true
const myPromise = new MyPromise((resolve, reject) => {
if (flag) {
resolve('nice')
} else {
reject('fuck')
}
})
myPromise
.then(res => {
console.log('then', res);
})
.catch(err => {
console.log('err', err);
})
class MyPromise {
status = 'pending'
value = null
reason = null
resolveCallback = null
rejectCallback = null
constructor (fn) {
const resolveHander = value => {
if (this.status === 'pending') {
this.status = 'fulfilled'
this.value = value
this.resolveCallback(this.value)
}
}
const rejectHander = reason => {
if (this.status === 'pending') {
this.status = 'rejected'
this.reason = reason
this.rejectCallback(this.reason)
}
}
fn(resolveHander, rejectHander)
}
then (fn1, fn2) {
fn1 = typeof fn1 === 'function' ? fn1 : v => v
fn2 = typeof fn2 === 'function' ? fn2 : r => r
if (this.status === 'pending') {
return new MyPromise((resolve, reject) => {
resolveCallback = () => {
resolve(fn1(this.value))
}
rejectCallback = () => {
reject(fn2(this.reason))
}
})
}
if (this.status === 'fulfilled') {
return new MyPromise((resolve, reject) => {
resolve(fn1(this.value))
})
}
if (this.status === 'rejected') {
return new MyPromise((resolve, reject) => {
reject(fn2(this.reason))
})
}
}
catch (fn1) {
this.then(null, fn1)
}
}
MyPromise.resolve = function (value) {
return new MyPromise((resolve, reject) => resolve(value))
}
MyPromise.reject = function (reason) {
return new MyPromise((resolve, reject) => reject(reason))
}
MyPromise.all = function (promiseList = []) {
return new MyPromise((resolve, reject) => {
const result = []
let resolveCount = 0
promiseList.forEach(p => {
p
.then(res => {
result.push(res)
resolveCount++
})
.catch(err => {
reject(err)
})
})
if (resolveCount === promiseList.length) {
resolve(result)
}
})
}
MyPromise.race = function (promiseList = []) {
return new MyPromise((resolve, reject) => {
let flag = false
promiseList.forEach(p => {
p
.then(res => {
if (!flag) {
resolve(res)
flag = true
}
})
.catch(err => {
reject(err)
})
})
})
}