文章目录

# 异步

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style> div { height: 30px; background: #8e44ad; width:0px ; display: flex; justify-content: center; align-items: center; font-size: 30px; color: #fff; } </style>
</head>

<body>
  <div id="loading">0%</div>
</body>
<script src="./dist/ajax.js"></script>
<script> function query(name) { let url = `http://localhost:3000` ; return ajax(`${url}/users?name=${name}`) ; } (async ()=>{ let users = ['茵蒂克丝','御坂美琴','白井黑子','佐天泪子','初春饰利']; let len = users.length; for(let i=0;i<len;i++) { let user = await query(users[i]) ; let progress = ((i+1)/len)*100; loading.style.width = progress+'%'; loading.innerHTML = Math.round(progress)+'%' ; console.log( user.length>0?user : '没有数据' ) } })() </script>
</html>

ajax.js
<mark>这里加了延时哦,为了看出效果</mark>

class ParamError extends Error{
  constructor(msg) {
    super(msg) ; 
    this.name = 'ParamError' ;
  }
}
class HttpError extends Error { 
  constructor(msg) {
    super(msg) ;
    this.name = 'HttpError' ;
  }
}
class WebAssert {
  static isURL(url) {
    if(!/^https?:\/\//i.test(url)) {
      throw new ParamError('请求地址格式错误')
    }
  }
}
function ajax(url) {
  return  new Promise((resolve, reject) => {
    WebAssert.isURL(url) ;
    let xhr = new XMLHttpRequest() ;
    xhr.open('GET', url) ;
    // xhr.readyState==4 ==> xhr.onload
    xhr.onload = function(result) {
      if(this.status == 200) {
        resolve(JSON.parse(this.response) ) ;
      }else if(this.status ==404) {
        // throw new HttpError('用户不存在'); 这样是不行的,因为在新线程里面
        reject(new HttpError('用户不存在'))
      }else{
        reject('加载失败')
      }
    }
    xhr.onerror = function() {
      reject(this)
    }
    setTimeout(() => {
      xhr.send() ;
    }, 1000);
  })
}

用了 mock工具 : jsonserver

其中 db.json

{
  "users": [
    {"id":1, "name":"御坂美琴", "email":"jdbc@qq.com"},
    {"id":2, "name":"茵蒂克丝", "email":"c3p0@qq.com"}
  ],
  "lessons": [
    {"id":1 ,"js":60, "ts":89},
    {"id":2 ,"js":33, "ts":10}
  ]
}

# 非异步

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style> * { padding: 0; margin: 0; } body { display: flex; font-size: 3em; padding: 30px; color: #34495e; } div { background: #3498db; text-align: center; } </style>
</head>

<body>
  <div id='hd'></div>
</body>

<script> function handle() { let i = 0; (function run() { hd.innerHTML = i + "%"; hd.style.width = i + "%"; if (++i <= 100) { setTimeout(run, 100); } })() } handle(); </script>

</html>