chiyan-lin / code-snippet

the record of something snippety
1 stars 0 forks source link

mock promise #15

Open chiyan-lin opened 4 years ago

chiyan-lin commented 4 years ago

class Promises {
  // 三种状态 pending(进行中)、fulfilled(已成功)和rejected(已失败)

  /**
     * 常用方式Promise.resolve(something).then(...)
     * 可见Promise.resolve返回一个新的Promise实例
     **/
  static resolve() { }

  static reject() { }

  status = 'pending'
  callback = () => { }

  constructor(fn) {
    fn(this._resolve.bind(this), this._reject)
  }

  _resolve(value) {
    this.callback(value)
  }

  _reject() {

  }

  then(fn) {
    this.callback = fn
  }
}

var aa = new Promises((resolve, reject) => {
  setTimeout(() => {
    resolve(1)
  }, 2000)
})

aa.then((value) => {
  console.log('value', value, this)
})