JavaScript: Promise async await

 

  1. 使用Promise封装ajax
    function ajax (url) {
      return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function () {
          if (this.readyState === 4) {
            if (this.status === 200) {
              console.log('resolve')
              resolve(this.responseText)
            } else {
              console.log('error',)
              reject(new Error('reject error'))
            }
          }
        }
        xhr.open('get', url)
        xhr.send()
      })
    
    }
      <script>
        function send () {
          ajax('http://localhost:555/vanity')
            .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err))
            .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err))
            .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err))
            .then(data => console.log(data), err => console.log(err))
        }
      </script>

     

  2. Promise实现
    class MyPromise {
      status = 'pending'  // 初始状态
      value = undefined
      reason = undefined
      onfulfilled = undefined
      onrejected = undefined
      constructor(executor) {
        console.log('constructor')
        executor(this.resolve, this.reject)
      }
    
      resolve = value => {
        console.log('resolve')
        if(this.status !== 'pending') return
        this.status = 'fulfilled'
        this.value = value
        this.onfulfilled && this.onfulfilled(this.value)
      }
    
      reject = reason => {
        console.log('reject')
        if(this.status !== 'pending') return
        this.status = 'rejected'
        this.reason = reason
        this.onrejected && this.onrejected(this.reason)
      }
    
      then(onfulfilled, onrejected) {
        console.log('call then')
        if(this.status === 'fulfilled') {
          console.log('then fulfilled')
          onfulfilled(this.value)
        } else if(this.status === 'rejected') {
          console.log('then reject')
          onrejected(this.reason)
        } else {  // 异步回调必定到此处
          console.log('then pending')
          this.onfulfilled = onfulfilled  // 为当前Promise对象绑定then的成功回调
          this.onrejected = onrejected  // 为当前Promise对象绑定then的失败回调
        }
      }
    }

    fs.readFile

    import fs from 'fs'
    
    let pp = new MyPromise((resolve, reject) => {
      fs.readFile('./a.txt', 'utf8', (err, data) => {
        if(err) {  // readFile异步回调进入EventLoop, 必定后于then执行
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
    // 绑定成功和失败的执行函数
    pp.then(data => console.log(data), err => console.log(err))

    new Date().getTime() 模拟

    let promise = new MyPromise((resolve, reject) => {
      setTimeout(() => {
        const timestamp = new Date().getTime()
        if(timestamp % 2) {
          resolve(`odd ${timestamp}`)
        } else {
          reject(`even ${timestamp}`)
        }
      },1000)
    })
    
    promise.then(value => {
      console.log('success', value)
    }, err => {
      console.log('fail', err)
    })

     

posted @ 2022-03-22 22:07  ascertain  阅读(21)  评论(0编辑  收藏  举报