promise的简易实现

在面试过程中,要求实现promise。如果你能实现出一个简易版的Promise 既可以过关了

// 创建三个常量用于表示状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(fn) {
    const that = this
    that.state = PENDING
    that.value = null // 保存resolve 或者 reject中传入的值
    // 用于保存then中的回调 当执行完promise状态可能还是等待中,需要把then中的回调保存
    that.resolvedCallbacks = []
    that.rejectedCallbacks = []


   function resolve(value) {
       if (that.state === PENDING){
           that.state = RESOLVED
           that.value = value
           that.resolvedCallbacks.map(cb=>cb(this.value))
       }
   }
   function reject(value) {
       if (that.state === PENDING){
           that.state = REJECTED
           that.value = value
           that.rejectedCallbacks.map(cb=>cb(that.value))
       }
   }
}
MyPromise.prototype.then = function (onFulfilled,onRejected) {
    const that = this
    onFulfilled = typeof  onFulfilled === 'function' ? onFulfilled: v=>v
    onRejected = typeof  onRejected === 'function' ? onRejected : v=>v

    if (that.state === PENDING){
        that.resolvedCallbacks.push(onFulfilled)
        that.rejectedCallbacks.push(onRejected)
    }
    if (that.state === RESOLVED){
        onFulfilled(that.value)
    }
    if (that.state === REJECTED){
        onRejected(that.value)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Promise的简易实现(1) 1.Promise的日常使用 举个栗子: 2.做出Promise大致框架 代码的大...
    SunnyEver0阅读 453评论 0 0
  • iOS 之 Promise简易实现 Promises/A的API规范 1. 有限状态机 Promise 有一个有...
    践行者阅读 5,730评论 6 9
  • 在上一篇文章里面,我们实现了一个简单的Promise,已可以满足一些较简单的场景。但却无法进行then的Promi...
    SunnyEver0阅读 304评论 0 0
  • promise 在完成符合Promis/A+规范之前,我们可以实现一个简易版Promise,因为在面试中,如果你能...
    豆芽y_阅读 1,100评论 0 14
  • https://www.jianshu.com/p/77a4f2c9d18b 手写 Promise 非常赞,看了简...
    peerben阅读 336评论 0 0