es6promise对象


// 将异步程序放入promise实例
// promise.js
const Ajaxs = (method, url, data) => {

  let promise = new Promise((resolve, reject) => {
    // ****
    let ajax = new XMLHttpRequest()

    if (method.toLocaleLowerCase() === 'get') {
      if (data) {
        ajax.open(method, url + '?' + data, true)
      } else {
        ajax.open(method, url, true)
      }
      ajax.send()
    } else {
      ajax.open(method, url, true)
      ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
      if (data) {
        ajax.send(data)
      } else {
        ajax.send()
      }
    }

    ajax.onreadystatechange = () => {
      if (ajax.readyState !== 4) {
        return
      }
      if (ajax.status === 200) {
        resolve(ajax.responseText)
      } else {
        reject(new Error(ajax.statusText))
      }
    }
    // ***
  });

  return promise
}
<script src="./promise.js"></script>

<script>

  // 接收一个promise对象
  let result = Ajaxs('get', './3.json', '666')
 
  console.log('result for 24 line', result); // result for 24 line Promise {<pending>}

  // 没有then和then之后的都是promise对象
  let type1 = result.then((res) => {        
    console.log('res', res); // 正常输出
  }, (err) => {
    console.log('err', err);
  })

  // .then 之后
  console.log('type1', type1);   // type1 Promise {<pending>} 
    
 </script>

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录