[js异步编程]手写一个Promise

/*
 * @Author: sunxy
 * @Date: 2021-07-08 23:33:30
 * @LastEditors: sunxy
 * @LastEditTime: 2021-07-11 23:30:18
 * @Description: 手写 promise
 * @FilePath: /feir/src/components/async.js
 */



//new Promise 
const PENDING  = 'pending' // 进行中
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败

class myPromise{
  // 构造函数
  constructor(executor){
    executor(this.resolve,this.reject)
  }
  status = PENDING
  value = undefined
  reason = undefined
  resolve = (value) => {
    // 只能是pending 状态才能修改
    if(this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    this.succCallback && this.succCallback(this.value)
  }
  reject = (reason) => {
    // 只能是pending 状态才能修改
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    this.failCallback && this.failCallback(this.reason)
  }

  succCallback = undefined
  failCallback = undefined
  then(succCallback,failCallback){
    if(this.status === FULFILLED){
      succCallback(this.value)
    }else if(this.status === REJECTED){
      failCallback(this.reason)
    }else{ // 正在pending 保存参数等到resole 或者 reject的时候再执行
      this.succCallback = succCallback
      this.failCallback = failCallback
    }
  }

}
// module.exports = myPromise

var p = new myPromise((resolve,reject) => {
  setTimeout(()=>{
    resolve('执行成功啦~')
  },3000)
})

p.then((res)=>{
  console.log('value',res)
})




你可能感兴趣的:([js异步编程]手写一个Promise)