1.promise解决的问题
- 回调地狱,多个异步请求嵌套时,第一个函数的输出是第二个函数的输入
- 处理多个异步请求并发
2.promise基础使用
const promise = new Promise((resolve,reject)=>{
console.log('promise')
resolve('success)
})
promise.then(
data =>{resolve(data)},
err=>{reject(err)}
)
3.promise原理及手写
-
promise三个状态:pending、fulfilled、rejected;默认状态时pending
-
const PENDING = 'PENDING'; const FULFILLED = 'FULFILLED'; const REJECTED = 'REJECTED' -
function Promise(executor){} -
promise 有一个value 用于保存成功状态的值,有一个reson 用于保存失败状态的值
-
function Promise(executor){ this.status = PENDING; this.value = undefined; this.reason = undefined; this.onFulfilledCallBack =[]; //成功回调 this.onRejectedCallBack = []; // 失败回调} -
promise 内置 executor执行器,执行器立即执行; executor接收两个参数 resolve 、reject
-
this.resolve = (value)=>{ if(this.status === PENDING){ this.status = FULFILLED; this.value = value this.onFulfilledCallBack.forEach(fn=>fn()) }} this.reject = (val)=>{ if(this.status === PENDING){ this.status = REJECTED this.reason = val this.onRejectedCallBack.forEach(fn=>fn())}} try{ executor(this.resovle,this.reject)}catch(err){ this.reject(err) } -
promise 状态变化只能从pending到rejected 或 pending到fulfilled,状态一旦确认,就不再改变
-
promise 必须有一个then方法,接收两个参数,分别是成功回调(onFulfilled) 、失败回调(onRejected),成功回调参数是promise的value,失败回调参数是promise的reason
-
this.then(onFulfilled,onRejected){ if(this.status === FELFILLED){ onFulfilled(this.value) } if(this.status === REJECTED){ onRejected(this.reason) } if(this.status === PENDING){ this.onFulfulledCallBack.push(()=>{onFulfilled(this.value)}) this.onRejectedCallBack.push(()=>{onRejected(this.reson)}) } } -
针对异步操作,因为promise调用then方法时,当前的promise还处于pending状态,所以需要先将成功和失败的回调函数保存到数组中,在executor()异步任务被执行时,触发resolve或reject,依次调用成功或失败的回调
// 存放成功的回调 this.onResolvedCallbacks = []; // 存放失败的回调 this.onRejectedCallbacks= [];