按照promise/A+规范
1、promise有三种状态,pending,fulfilled,rejected, 且状态只能从pending变为fulfilled或从pending变为rejected,状态一旦发生变化就不能改变
2、Fulfilled:promise必须有一个不可变的终值value
3、Rejected:promise必须拥有一个不可变的据因reason
4、promise是具有then方法的对象或函数,该方法接受两个函数参数,分别为onFulfilled,onRejected,可以访问到终值和据因
5、promise是立即执行的
const PENDING = 'Pending'
const FULFILLED = 'Fulfilled'
const REJECTED = 'Rejected'
class Promise {
// 高阶函数,函数的参数是函数,高阶函数可以实现参数的预置
// 函数的参数中的函数为函数的声明
// executor是立即执行的函数,参数被预置在了constructor中
constructor(executor) {
this.state = PENDING
this.value = undefined // 成功的结果
this.reason = undefined // 失败的理由
const resolve = (value) => {
if(this.state === PENDING) {
this.state = FULFILLED
this.value = value
}
}
const reject = (reason) => {
if(this.state === PENDING) {
this.state = REJECTED
this.reason = reason
}
}
// 此处为executor函数的调用。参数传入resolve和reject两个函数
try {
executor(resolve, reject)
} catch(err) {
reject(err)
}
}
then(onFulfilledCallback, onRejectedCallback) {
onFulfilledCallback = typeof onFulfilledCallback === 'function' ? onFulfilledCallback : value => value
onRejectedCallback = typeof onRejectedCallback === 'function' ? onRejectedCallback : reason => reason
if(this.state === FULFILLED) {
onFulfilledCallback(this.value)
}
if(this.state === REJECTED) {
onRejectedCallback(this.reason)
}
}
}
new Promise((resolve, reject) => {
resolve(1)
}).then((res) => {
console.log(res)
})
执行结果:1