promise(Promise 用法,fetch用法,axios用法,async/await用法)

1.Promise 用法

1.1 异步调用

异步效果分析
  1. 定时任务
  2. Ajax
  3. 事件函数
多次异步调用的依赖分析
  1. 多次异步调用的结果顺序不确定
  2. 异步调用结果如果存在依赖需要嵌套

1.2 Promise 概述

Promise 是异步编程的一种解决方案,从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。

使用 Promise 主要有以下好处:

  1. 可以避免多层异步调用嵌套问题(回调地狱)
  2. Promise 对象提供了简洁的API,使得控制异步操作更加容易

1.3 Promise 基本用法

  1. 实例化 Promise 对象,构造函数中传递函数,该函数中用于处理异步任务
var p = new Promise(function(resolve, reject){
   // 成功时调用 resolve()
   // 失败时调用 reject()
 });

  1. resolve 和 reject 两个参数用于处理成功和失败两种情况,并通过 p.then 获取处理结果
p.then(funciton(ret){
     // 从resolve得到正常结果
  }, function(ret){
     // 从reject得到错误信息
  });
案例:Promise基本使用
  <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>

1.4 基于Promise处理Ajax请求

1. 处理原生Ajax
 function queryData(){
  return new Promise(function(resolve,reject){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
      if(xhr.readyState !=4) return;
      if(xhr.status == 200) {
        resolve(xhr.responseText)
      }else{
        reject('出错了');
      }
    }
    xhr.open('get', '/data');
    xhr.send(null);
  })
 }

2. 发送多次ajax请求
.then(function(data){
    return queryData();
  })
  .then(function(data){
    return queryData();
  })
  .then(function(data){
    return queryData();
  });

1.5 then参数中的函数返回值

1. 返回 Promise 实例对象

返回的该实例对象会调用下一个 then

2. 返回普通值

返回的普通值会直接传递给下一个 then,通过 then 参数中函数的参数接收该值

    /*
      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)
      })

1.6 Promise常用的API

1. 实例方法
  • p.then() 得到异步任务的正确结果
  • p.catch() 获取异常信息
  • p.finally() 成功与否都会执行(尚且不是正式标准)
2. 对象方法

Promise.all() 并发处理多个异步任务,所有任务都执行完成才能得到结果

Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果

Promise.all([p1,p2,p3]).then((result) => {
   console.log(result)
 })

 Promise.race([p1,p2,p3]).then((result) => {
   console.log(result)
 })

<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>

2.接口调用-fetch用法

2.1 fetch 概述

1. 基本特性
  • 更加简单的数据获取方式,功能更强大、更灵活,可以看做是xhr的升级版
  • 基于Promise实现
2. 语法结构
fetch(url).then(fn2)
            .then(fn3)
            ...
            .catch(fn)

2.2 fetch 的基本用法

fetch('/abc').then(data=>{
      return data.text();
  }).then(ret=>{
      // 注意这里得到的才是最终的数据
      console.log(ret);
  });

2.3 fetch请求参数

1. 常用配置选项
  • method(String): HTTP请求方法,默认为GET (GET、POST、PUT、DELETE)
  • body(String): HTTP的请求参数
  • headers(Object): HTTP的请求头,默认为{}
fetch('/abc' , {
    method:get}).then(data=>{
    return data.text();
 }).then(ret=>{
    // 注意这里得到的才是最终的数据
    console.log(ret);
 });

2. GET请求方式的参数传递
fetch(/abc?id=123).then(data=>{
    return data.text();
 }).then(ret=>{
    // 注意这里得到的才是最终的数据
    console.log(ret);
 });

3. DELETE请求方式的参数传递
 fetch(/abc/123' ,{
    method:delete}).then(data=>{
    return data.text();
 }).then(ret=>{
    // 注意这里得到的才是最终的数据
    console.log(ret);
 });

4. POST请求方式的参数传递
 fetch(/books' ,{
    method: ‘post’,
    body: ‘uname=lisi&pwd=123,
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded‘,
    }
 }).then(data=>{
    return data.text();
 }).then(ret=>{
    console.log(ret);
 });

5. PUT请求方式的参数传递
 fetch(/books/123' ,{
    method: ‘put’,
    body: JSON.stringify({
       uname: ‘lisi’,
       age: 12
    })
    headers: {
       'Content-Type': 'application/json ‘,
    }
 }).then(data=>{
    return data.text();
 }).then(ret=>{
    console.log(ret);
 });

2.4 fetch响应结果

响应数据格式
  • text(): 将返回体处理成字符串类型
  • json():返回结果和 JSON.parse(responseText)一样
 fetch('/abc' then(data=>{
    // return data.text();
    return data.json();
 }).then(ret=>{
    console.log(ret);
 });

3.接口调用-axios用法

3.1 axios 的基本特性

axios(官网:https://github.com/axios/axios)是一个基于Promise 用于浏览器和 node.js 的 HTTP 客户端。

它具有以下特征:

  • 支持浏览器和 node.js
  • 支持 promise
  • 能拦截请求和响应
  • 自动转换 JSON 数据

3.2 axios 的基本用法

axios.get(/adata')
       .then(ret=>{
          // data属性名称是固定的,用于获取后台响应的数据
          console.log(ret.data)
       })

3.3 axios 的常用API

  • get : 查询数据
  • post : 添加数据
  • put : 修改数据
  • delete :删除数据

3.4 axios 的参数传递

1. GET传递参数
  • 通过 URL 传递参数
  • 通过 params 选项传递参数
axios.get(/adata?id=123')
       .then(ret=>{
          console.log(ret.data)
       })
axios.get(/adata/123')
       .then(ret=>{
          console.log(ret.data)
       })

axios.get(/adata‘,{
          params: {
            id: 123
          }
       })
       .then(ret=>{
          console.log(ret.data)
       })

2. DELETE传递参数
  • 参数传递方式与GET类似
axios.delete(/adata?id=123')
       .then(ret=>{
          console.log(ret.data)
       })

axios.delete(/adata/123')
       .then(ret=>{
          console.log(ret.data)
       })

axios.delete(/adata‘,{
          params: {
            id: 123
          }
       })
       .then(ret=>{
          console.log(ret.data)
       })

3. POST传递参数
  • 通过选项传递参数(默认传递的是 json 格式的数据)
  axios.post(/adata',{
    uname: 'tom',
    pwd: 123
  }).then(ret=>{
    console.log(ret.data)
  })

  • 通过 URLSearchParams 传递参数(application/x-www-form-urlencoded)
   const params = new URLSearchParams();
   params.append('param1', 'value1');
   params.append('param2', 'value2');
   axios.post('/api/test', params).then(ret=>{
      console.log(ret.data)
   })

4. PUT传递参数

参数传递方式与POST类似

  axios.put(/adata/123',{
    uname: 'tom',
    pwd: 123
  }).then(ret=>{
    console.log(ret.data)
  })

3.5 axios 的响应结果

响应结果的主要属性

  • data : 实际响应回来的数据
  • headers :响应头信息
  • status :响应状态码
  • statusText :响应状态信息
axios.post('/axios-json‘).then(ret=>{
    console.log(ret)
  })

3.6 axios 的全局配置

axios.defaults.timeout = 3000;   // 超时时间
axios.defaults.baseURL = 'http://localhost:3000/app';  // 默认地址
axios.defaults.headers[‘mytoken’] = ‘aqwerwqwerqwer2ewrwe23eresdf23’// 设置请求头

1. 请求拦截器

promise(Promise 用法,fetch用法,axios用法,async/await用法)_第1张图片

//添加一个请求拦截器
  axios.interceptors.request.use(function(config){
    //在请求发出之前进行一些信息设置
    return config;
  },function(err){
    // 处理响应的错误信息
  });

2. 响应拦截器

promise(Promise 用法,fetch用法,axios用法,async/await用法)_第2张图片

//添加一个响应拦截器
  axios.interceptors.response.use(function(res){
    //在这里对返回的数据进行处理
    return res;
  },function(err){
    // 处理响应的错误信息
  })

4.接口调用-async/await用法

5.1 async/await 的基本用法

  • async/await是ES7引入的新语法,可以更加方便的进行异步操作
  • async 关键字用于函数上(async函数的返回值是Promise实例对象)
  • await 关键字用于 async 函数当中(await可以得到异步的结果)
 async function queryData(id) {
    const ret = await axios.get('/data');
    return ret;
  }
  queryData.then(ret=>{
    console.log(ret)
  })

5.2 async/await 处理多个异步请求

  async function queryData(id) {
    const info = await axios.get('/async1');
    const ret = await axios.get(‘async2?info=+info.data);
    return ret;
  }
  queryData.then(ret=>{
    console.log(ret)
  })

你可能感兴趣的:(前端方法的总结及记录,归纳,javascript,前端,html5)