promise原理
1. 什么事promise?
Promise是JS异步编程中的重要概念,异步抽象处理对象,是目前比较流行Javascript异步编程解决方案之一
-
promise方法分析
-
promise创建的是一个微任务 当主线程执行完在执行微任务(promise)
-
promise状态
-
待定(pending):初始状态,既没有被兑现,也没有被拒绝。
-
已兑现(fulfilled):意味着操作成功完成。
-
已拒绝(rejected):意味着操作失败。
prosmise 对象方法 resolve和reject方法
```javascript
class selfPromis {
static PENDING = "pending" //待定(pending)
static FUFILLED = "fulfilled" //已兑现(fulfilled)
static REJECTED = "reject" //已拒绝(rejected)
//传入callBack回调函数
constructor(callBack) {
this.status = selfPromis.PENDING;
this.value = null;
//需要人为干预 promise 的 this指针 因为 class默认是严格模式 this 为定义
//需要把指针指向调用者
this.callbacks = [] //存放宏任务数组 satTimeout
try {
callBack(this.resolve.bind(this), this.reject.bind(this))
} catch (error) {
this.reject(error)
}
}
}
resolve方法
resolve(value) {
//首先判断 当前状态 为了 防止状态更改 调用的时候需要 对状态进行判断
if (this.status == selfPromis.PENDING) {
this.status = selfPromis.FUFILLED
this.value = value
//当then中的 setTimeout执行完后 轮询 callbacks 数组 执行 成功方法
this.callbacks.map(callback => {
// console.log(this.value)
callback.onFulfilled(this.value)
})
}
}
**reject方法**
reject(value) {
//首先判断 当前状态 为了 防止状态更改 调用的时候需要 对状态进行判断
if (this.status == selfPromis.PENDING) {
this.status = selfPromis.REJECTED
this.value = value
//当then中的 setTimeout执行完后 轮询 callbacks 数组 执行 失败方法
this.callbacks.map(callback => {
callback.onReject(this.value)
})
}
}
then的链式调用
1.首先then会递归返回一个promise对象
2.then方法需要两个参数,第一个参数作为处理已兑现状态的回调函数,第二个参数则作为处理已拒绝状态的回调函,数每一个 .then() 方法还会返回一个新生成的 promise 对象,这个对象可被用作链式调用
then(onFulfilled, onReject) {
// 处理兼容性问题 当为参传输是 乃然运行
if (typeof onFulfilled != "function") onFulfilled = () => this.value //解决then的穿透
if (typeof onReject != "function") onReject = () => this.value //解决then的穿透
//等待状态 因为 当then 用到 setTimeout 创建出来宏任务 会有异步操作
let promise = new selfPromis((resolve, reject) => {
if (this.status == selfPromis.PENDING) {
this.callbacks.push({
onFulfilled: value => {
this.param(onFulfilled(promise, value), resolve, reject)
},
onReject: value => {
this.param(promise, onReject(value), resolve, reject)
}
})
}
console.log(this.status)
// then的链式写法 当状态 改变为成功调用
if (this.status == selfPromis.FUFILLED) {
setTimeout(() => {
this.param(promise, onFulfilled(this.value), resolve, reject)
});
}
// then的链式写法 当状态 改变为拒接调用
if (this.status == selfPromis.REJECTED) {
setTimeout(() => {
this.param(promise, onReject(this.value), resolve, reject)
});
}
})
return promise;
}
静态resolve
static resolve(value) {
return new selfPromis((resolve, reject) => {
if (value instanceof selfPromis) {
value.then(resolve, reject);
} else {
resolve(value)
}
})
}
静态reject
static reject(value) {
return new selfPromis((resolve, reject) => {
reject(value)
})
}