1、大纲

1220447-20200228100558882-656497853.png
1220447-20200228100750811-1842627952.png

2、前后端交互方式

1220447-20200228100916375-168018152.png
1220447-20200228101105435-2124857335.png
1220447-20200228101237998-1890060299.png
1220447-20200228101327621-1404915112.png
1220447-20200228101558857-434192075.png

3、Promise使用

异步
  • JavaScript的执行环境是「单线程」
  • 所谓单线程,是指JS引擎中负责解释和执行JavaScript代码的线程只有一个,也就是一次只能完成一项任务,这个任务执行完后才能执行下一个,它会「阻塞」其他任务。-* 这个任务可称为主线程
  • 异步模式可以一起执行多个任务,但多次异步调用的顺序不确定,不是按照我们写代码的顺序得到结果
  • 如果异步调用结果存在依赖,代码需要嵌套

    JS中常见的异步调用
  • 定时任务
  • ajax
  • 事件函数

1220447-20200228102314949-253008814.png

1220447-20200228102807066-632914762.png


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div>前后端交互</div>
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
    /*
      前后端交互-异步编程与Promise概述
    */
    // var ret = '---';
    // $.ajax({
    //   url: 'http://localhost:3000/data',
    //   success: function(data) {
    //     ret = data;
    //     console.log(ret)
    //   }
    // });
    // console.log(ret)

    // ----------------------------
    // $.ajax({
    //   url: 'http://localhost:3000/data',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // $.ajax({
    //   url: 'http://localhost:3000/data1',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // $.ajax({
    //   url: 'http://localhost:3000/data2',
    //   success: function(data) {
    //     console.log(data)
    //   }
    // });
    // -----------------------------------
    $.ajax({
      url: 'http://localhost:3000/data',
      success: function(data) {
        console.log(data)
        $.ajax({
          url: 'http://localhost:3000/data1',
          success: function(data) {
            console.log(data)
            $.ajax({
              url: 'http://localhost:3000/data2',
              success: function(data) {
                console.log(data)
              }
            });
          }
        });
      }
    });
    
    
    
  </script>
</body>
</html>

1220447-20200228104930263-520659862.png
1220447-20200228105039822-148378275.png
1220447-20200228105404715-1187621306.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise基本使用
    */
    // console.log(typeof Promise)
    // console.dir(Promise);

    var p = new Promise(function(resolve, reject){
      // 这里用于实现异步任务
      setTimeout(function(){
        var flag = false;
        if(flag) {
          // 正常情况
          resolve('hello');
        }else{
          // 异常情况
          reject('出错了');
        }
      }, 100);
    });
    p.then(function(data){
      console.log(data)
    },function(info){
      console.log(info)
    });
  </script>
</body>
</html>

1220447-20200228105919171-1405967407.png

1220447-20200228110301836-288921577.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      基于Promise发送Ajax请求
    */
    function queryData(url) {
      var p = new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 处理正常的情况
            resolve(xhr.responseText);
          }else{
            // 处理异常情况
            reject('服务器错误');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }
    // queryData('http://localhost:3000/data')
    //   .then(function(data){
    //     console.log(data);
    //   },function(info){
    //     console.log(info)
    //   });
    // ============================
    // 发送多个ajax请求并且保证顺序
    queryData('http://localhost:3000/data')
      .then(function(data){
        console.log(data)
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        return queryData('http://localhost:3000/data2');
      })
      .then(function(data){
        console.log(data)
      });
  </script>
</body>
</html>

1220447-20200228111531328-374159904.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      then参数中的函数返回值
    */
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 处理正常的情况
            resolve(xhr.responseText);
          }else{
            // 处理异常情况
            reject('服务器错误');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }
    queryData('http://localhost:3000/data')
      .then(function(data){
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        return new Promise(function(resolve, reject){
          setTimeout(function(){
            resolve(123);
          },1000)
        });
      })
      .then(function(data){
        return 'hello';
      })
      .then(function(data){
        console.log(data)
      })

  </script>
</body>
</html>

1220447-20200228111905258-668282141.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise常用API-实例方法
    */
    // console.dir(Promise);
    function foo() {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          // resolve(123);
          reject('error');
        }, 100);
      })
    }
    // foo()
    //   .then(function(data){
    //     console.log(data)
    //   })
    //   .catch(function(data){
    //     console.log(data)
    //   })
    //   .finally(function(){
    //     console.log('finished')
    //   });

    // --------------------------
    // 两种写法是等效的
    foo()
      .then(function(data){
        console.log(data)
      },function(data){
        console.log(data)
      })
      .finally(function(){
        console.log('finished')
      });
  </script>
</body>
</html>

1220447-20200228112319666-733985154.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Promise常用API-对象方法
    */
    // console.dir(Promise)
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 处理正常的情况
            resolve(xhr.responseText);
          }else{
            // 处理异常情况
            reject('服务器错误');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }

    var p1 = queryData('http://localhost:3000/a1');
    var p2 = queryData('http://localhost:3000/a2');
    var p3 = queryData('http://localhost:3000/a3');
    // Promise.all([p1,p2,p3]).then(function(result){
    //   console.log(result)
    // })
    Promise.race([p1,p2,p3]).then(function(result){
      console.log(result)
    })
  </script>
</body>
</html>

1220447-20200228112710096-1479965803.png
1220447-20200228112756607-717880800.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Fetch API 基本用法
    */
    fetch('http://localhost:3000/fdata').then(function(data){
      // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
      return data.text();
    }).then(function(data){
      console.log(data);
    })
  </script>
</body>
</html>

1220447-20200228113051072-614044490.png
1220447-20200228113316443-1078978070.png
1220447-20200228113526904-834503095.png
1220447-20200228113753744-396029405.png
1220447-20200228113909632-1254390003.png
1220447-20200228113947428-1835622452.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script type="text/javascript">
    /*
      Fetch API 调用接口传递参数
    */

    // GET参数传递-传统URL
    // fetch('http://localhost:3000/books?id=123', {
    //   method: 'get'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // GET参数传递-restful形式的URL
    // fetch('http://localhost:3000/books/456', {
    //   method: 'get'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // DELETE请求方式参数传递
    // fetch('http://localhost:3000/books/789', {
    //   method: 'delete'
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // POST请求传参
    // fetch('http://localhost:3000/books', {
    //   method: 'post',
    //   body: 'uname=lisi&pwd=123',
    //   headers: {
    //     'Content-Type': 'application/x-www-form-urlencoded'
    //   }
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // POST请求传参
    // fetch('http://localhost:3000/books', {
    //   method: 'post',
    //   body: JSON.stringify({
    //     uname: '张三',
    //     pwd: '456'
    //   }),
    //   headers: {
    //     'Content-Type': 'application/json'
    //   }
    // })
    //   .then(function(data){
    //     return data.text();
    //   }).then(function(data){
    //     console.log(data)
    //   });

    // PUT请求传参
    fetch('http://localhost:3000/books/123', {
      method: 'put',
      body: JSON.stringify({
        uname: '张三',
        pwd: '789'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
  </script>
</body>
</html>

1220447-20200228114103343-1889059501.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    /*
      Fetch响应结果的数据格式
    */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json();
      return data.text();
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })
  </script>
</body>
</html>
Logo

前往低代码交流专区

更多推荐