let PENDING = 'PENDING'
let FULFILLED = 'FULFILLED'
let REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
this.status = PENDING
this.value = undefined
this.reason = undefined
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
let resolve = value => {
if(this.status === PENDING) {
this.status = FULFILLED
this.value = value
this.onFulfilledCallbacks.forEach(onFulfilled => onFulfilled()) // 对异步任务的处理
}
}
let reject = reason => {
if(this.status === PENDING) {
this.status = REJECTED
this.reason = reason
this.onRejectedCallbacks.forEach(onRejected => onRejected()) // 对异步任务的处理
}
}
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : r => { return r }
onRejected = typeof onRejected === 'function' ? onRejected : j => { return j }
return new Promise((resolve, reject) => {
if(this.status === FULFILLED) {
try {
let ret = onFulfilled(this.value)
if(ret instanceof Promise) {
ret.then(resolve, reject)
} else {
resolve(ret)
}
} catch(e) {
reject(e)
}
}
if(this.status === REJECTED) {
try {
let ret = onRejected(this.reason)
if(ret instanceof Promise) {
ret.then(resolve, reject)
} else {
reject(ret)
}
} catch(e) {
reject(ret)
}
}
if(this.status === PENDING) {
this.onFulfilledCallbacks.push(() => {
try {
let ret = onFulfilled(this.value)
if(ret instanceof Promise) {
ret.then(resolve, reject)
} else {
resolve(ret)
}
} catch(e) {
reject(e)
}
})
this.onRejectedCallbacks.push(() => {
try {
let ret = onRejected(this.reason)
if(ret instanceof Promise) {
ret.then(resolve, reject)
} else {
reject(ret)
}
} catch(e) {
reject(ret)
}
})
}
})
}
catch(onRejected) { // catch方法其实就是对then方法的调用
return this.then(null, onRejected)
}
}
new Promise(((resolve,reject)=>{
console.log(1);
resolve();
})).then(new Promise(((resolve,reject)=>{
console.log(1);
reject();
})).then(res=>{
console.log(2)
return 3;
},res=>{
console.log(3)
return 4;
}))
console