1. 程式人生 > 其它 >實現一個簡易Promise

實現一個簡易Promise

class Promise2 {
  state = 'pending'
  succeed = null
  fail = null

  resolve(result) {
    // console.log('resolve', result)
    setTimeout(() => {
      this.state = 'fulfilled'
      this.succeed(result)
    })
  }

  reject(err) {
    // console.log('reject', err)
    setTimeout(() => {
      this.state = 'rejected'
      this.fail(err)
    })
  }

  constructor(fn) {
    fn(this.resolve.bind(this), this.reject.bind(this))
  }

  then(succeed, fail) {
    this.succeed = succeed
    this.fail = fail
  }
}
  • 測試是否可用
const getWeather = city => new Promise2((resolve, reject) => {
  let xhr = new XMLHttpRequest()
  xhr.open('GET', 'http://rap2api.taobao.org/app/mock/244238/getWeather?city='+city, true)
  xhr.onload = () => {
    if(xhr.status === 200) {
      resolve(JSON.parse(xhr.responseText))
    } else {
      reject(`獲取${city}天氣失敗`)
    }
  }
  xhr.send()
})

getWeather('北京')
  .then(data => { 
    console.log(data)
  }, err => {
    console.log(err)
  })
  • mock介面正常時

  • mock介面404時