基于Promise手动封装ajax

promise-ajax.js

function ajax({url='xxx', type="get", dataType="json"}) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open(type, url, true);
    xhr.responseType = dataType;
    xhr.onload = function () { // xhr.readState=4 xhr.status=200
      if(xhr.status == 200){
        resolve(xhr.response) //成功调用成功的方法
      }else{
        reject('not found');
      }
    };
    xhr.onerror = function (err) {
        reject(err) // 失败调用失败的方法
    };
    xhr.send();
  })
}

使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<body>
  <div id="app"></div>
  <script src="node_modules/vue/dist/vue.js"></script>
  <script src="promise-ajax.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      created(){
        ajax({url: './carts.json'}).then((res)=>{
          console.log(res)
        }, (err)=>{
          console.log(err)
        })
      },
      data: {
        products: []
      }
    })
  </script>
</body>
</html>