当前位置:网站首页>高阶函数的应用:手写Promise源码(二)

高阶函数的应用:手写Promise源码(二)

2022-07-23 05:39:00 Vivqst

目的:
1、当executor中有异步任务时,then执行的时候,状态还没发生变化,导致then中的回调不执行
2、Promise的特点是可以多次调用then方法

// promise/A+规范中说明promise有三种状态,且状态一旦被改变就不能再次发生变化
const PENDING = 'Pending'
const FULFILLED = 'Fulfilled'
const REJECTED = 'Rejected'
class Promise {
    
  // 高阶函数,函数的参数是函数,高阶函数可以实现参数的预置
  // 函数的参数中的函数为函数的声明
  // executor是立即执行的函数,参数被预置在了constructor中
  constructor(executor) {
    
    this.state = PENDING
    this.value = undefined         // 成功的结果
    this.reason = undefined        // 失败的理由
    
    // 解决then可以多次调用的问题
    this.onResolvedCallbacks = []   
    this.onRejectedCallbacks = []

    const resolve = (value) => {
    
      if(this.state === PENDING) {
    
        this.state = FULFILLED
        this.value = value
        // 当状态变化时再执行回调函数
        this.onResolvedCallbacks.forEach(cb => cb(value))
      }
    }

    const reject = (reason) => {
    
      if(this.state === PENDING) {
    
        this.state = REJECTED
        this.reason = reason
        // 当状态变化时再执行回调函数
        this.onRejectedCallbacks.forEach(cb => cb(reason))
      }
    }
   
    // 此处为executor函数的调用。参数传入resolve和reject两个函数
    try {
    
      executor(resolve, reject)
    } catch(err) {
    
      reject(err)
    }
  }
  then(onFulfilledCallback, onRejectedCallback) {
    
    onFulfilledCallback = typeof onFulfilledCallback === 'function' ? onFulfilledCallback : value => value
    onRejectedCallback = typeof onRejectedCallback === 'function' ? onRejectedCallback : reason => reason

    if(this.state === FULFILLED) {
    
   		onFulfilledCallback(this.value)
    }
    
    if(this.state === REJECTED) {
    
    	onRejectedCallback(this.reason)
    }
    
    // 当executor出现异步任务时,then执行的时候,状态还未发生变化,可以将回调放到回调函数数组中
    if(this.state === PENDING) {
    
      this.onResolvedCallbacks.push(onFulfilledCallback) 
      this.onRejectedCallbacks.push(onRejectedCallback)   
    }
  }
}

let p = new Promise((resolve, reject) => {
    
	console.log(2)
	setTimeout(() => {
    
		resolve(1)
	}, 0)
})
p.then((res) => {
    
	console.log(res)
})
p.then((res) => {
    
	console.log(res)
})
// 2, 1, 1
原网站

版权声明
本文为[Vivqst]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qiansitong/article/details/125642295