首页 > 其他 > 详细

实现一个简易Promise

时间:2021-06-12 00:44:46      阅读:25      评论:0      收藏:0      [点我收藏+]
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时
    技术分享图片

实现一个简易Promise

原文:https://www.cnblogs.com/c1nema/p/14876183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!