-
在封装前,我们要理解promise的基本使用过程
-
首先 Promise 就是一个类(构造函数),因为在使用的时候我们要
new Promise() -
在这个类执行的时候需要传递一个执行器进去,这个执行器会立即执行,这个执行器传进两个参数分别是 resolve 和 reject
new Promise((resolve, reject)=>{}) -
Promise 有三种状态,分别是
pendingrejectedfulfilled -
promise 的状态只能改变一次
pending=>rejectedpending=>fulfilled
-
Pomise 的
resolvereject是用来更改Promise状态的resolve将状态更改至成功reject将状态更改至失败
-
then 方法内部做的事情就是判断状态并返回像相应的数据
-
let promise = new Promise((resolve,reject) => {
resolve('成功')
reject('失败')
})
promise.then(
(value) => {
console.log(value)
},
(reason) => {
console.log(reason)
}
)
实现基础版Promise
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECT = 'reject'
class MyPromise {
// 用于接收外界传递的执行器
constructor(exctor) {
exctor(this.resolve, this.reject)
}
// 当前 promise 状态
status = PENDING
// 记录 promise 成功的数据
value = null
// 记录 promise 失败的原因
reason = null
// 成功的方法
resolve = (value) => {
if(this.status !== PENDING) return
this.status = FULFILLED
this.value = value
}
// 失败的方法
reject = (reason) => {
if(this.status !== PENDING) return
this.status = REJECT
this.reason = reason
}
// then 方法用于获取 promise 数据
then (successCallback, failCallback) {
if(this.status == FULFILLED) {
successCallback(this.value)
} else if (this.status == REJECT) {
failCallback(this.reason)
}
}
}
const myPromise = new MyPromise((resolve, reject) => {
resolve('成功')
reject('失败')
})
myPromise.then((value) => {
console.log(value);
}, (reason) => {
console.log(reason);
})