前端笔试题(4)-手写promise

1.promise的概念

a :异步 b:三个状态 等待=>成功\失败(状态不可逆转)


const promise =new Promise((resolve,reject)=>{
  console.log(1)
  resolve()
  console.log(2)
})

promise.then(()=>{
  console.log(3)
})
console.log(4)
// 1243
// 构造函数立即执行(同步) .then异步执行
const promise = new Promise((resolve,reject)={
  setTimeout(()=>{
    console.log(1)
    resolve(2)
  },1000)
})

promise.then((res)={
  console.log(res)
})
promise.then((res)=>{
  console.log(res)
})
// 122
// 构造函数只执行一次,.then可以多次执行

2.手写一个Promise


function myPromise(excutor){
  let self = this
  self.status = 'pending' //状态
  self.value = null //成功的结果
  self.reason = null //失败的原因
  self.onFulfilledCallbacks = []//存储
  self.onRejectedCallbacks = []
  // 成功的回调
  function resolve(value){
    // 状态处理
    if(self.status === 'pending'){
      	self.value = value //保存成功的结果
        self.status === 'fulfilled'
        self.onFulfilledCallbacks.forEach(item => item(value))//发布
    }
  }
  // 失败的回调
  function reject(reason){
    if(self.status === 'pending'){
        self.reason = reason //保存失败的原因
        elf.status === 'rejected'
        self.onRejectedCallbacks.forEach(item => item(reason))//发布
    }
  }
  // 立即执行一遍
  try{
    excutor(resolve,resject)
  }catch(err){
    reject(err)
  }

}
// then方法
myPromise.prototype.then =function(onFulfilled,onRejected){
  // 状态改变,走.then
  onFulfilled = typeof onFulfilled === 'function' ?
  onFulfilled : function(data){resolve(data)}
  onRejected = typeof onRejected === 'function' ?
  onRejected : function(err){throw err}
  // 发布订阅模式  订阅
  if(this.status=='pending'){
    this.onFulfilledCallbacks.push(onFulfilled)
    this.onRejectedCallbacks.push(onRejected)
  }
}

let demo = new myPromise((resolve,reject)=>{
  console.log('完成')
  setTimeout(()=>{
    resolve(123)
  },1000)
})
demo.then(data=>console.log(data))
posted @ 2023-04-04 14:37  FAIGEL  阅读(92)  评论(1)    收藏  举报