promise特点
- Promise 具有链式调用 解决回调地狱问题
- then 方法 接收成功回调
- catch 方法 接受失败回调
- Promise 有三个状态 Pending(等待状态) fulfilled(成功状态) rejected(失败状态) ,Promises/A+ 规范中明确规定了,pending 可以转化为 fulfilled 或 rejected 并且只能转化一次,也就是说如果 pending 转化到 fulfilled 状态,那么就不能再转化到 rejected。并且 fulfilled 和 rejected 状态只能由 pending 转化而来,两者之间不能互相转换。
实现一个Promise类(参数是一个函数 函数接收两个参数 两个参数也都是函数)
class Promise {
status = 'pending' // 初始化等待状态
value = null
constructor(fn) {
fn(this._resolve.bind(this),this._reject.bind(this))
}
_resolve(value) {
this.status = 'fulfilled'
this.value = value
}
_reject(error) {
this.status = 'rejected'
this.value = error
}
}
- 定义了一个Promise 类 类中定义了_resolve,_reject两个函数 在new Promise 类的时候将这个两个函数抛出去给外部用 外部只需要传递一个参数 这个参数 会 被传递到 then 中 或者是 catch中 使用bind 方法 主要是重新改变 一下 this 指向
实现一个Promise类(增加then 方法)
class Promise {
status = 'pending' // 初始化等待状态
value = null
constructor(fn) {
fn(this._resolve.bind(this),this._reject.bind(this))
}
_resolve(value) {
this.status = 'fulfilled'
this.value = value
}
_reject(error) {
this.status = 'rejected'
this.value = error
}
then(fn) {
if(this.status === 'fulfilled') {
fn(this.value)
}
return this
}
}
- then方法 需要判断下 promise 现在的状态 只有当 状态是 'fulfilled' 才执行回调函数 并把在 _resolve 接收到的值 传递给then
实现一个Promise类(增加catch 方法)
class Promise {
status = 'pending' // 初始化等待状态
value = null
constructor(fn) {
try {
fn(this._resolve.bind(this),this._reject.bind(this))
}catch(error) {
this._reject(error)
}
}
then(fn) {
if(this.status === 'fulfilled') {
try {
fn(this.value)
}catch(error) {
this._reject(error)
}
}
return this
}
_resolve(value) {
this.status = 'fulfilled'
this.value = value
}
_reject(error) {
this.status = 'rejected'
this.value = error
}
catch(efn) {
if(this.status === 'rejected') {
efn(this.value)
}
return this
}
}
- 用 try catch 接收异常 接收到异常就走_reject 修改状态为'rejected' 并且在 then 和 catch 方法中return Promise 实例出去 让它可以链式调用 最终走catch 并且接收_reject 传进来的值