Blogger Information
Blog 94
fans 0
comment 0
visits 92759
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】异步: fetch api 及 async,await 简化异步回调
可乐随笔
Original
1413 people have browsed it

异步请求: fetch api

1.标准fetch api请求

fetch: 是浏览器自带的原生的异步解决方案API
代码简洁:fetch(url).then().then().catch();
代码解释:

第一个.then fetch拿回来的数据,在then中执行,将对象(response)json序列化
第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出

fetch HTML代码示范:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>异步请求: fetch api</title>
  8. </head>
  9. <body>
  10. <button onclick="getUser(this)">Fetch API</button>
  11. <script>
  12. function getUser() {
  13. fetch('http://ajaxtest.cn/data.php?id=3')
  14. .then((response) => response.json())
  15. .then((json) => console.log(json));
  16. }
  17. </script>
  18. </body>
  19. </html>

2.async,await 简化异步回调

ECMA2017: async,await 简化异步回调
将函数异步化: 异步函数, async
内部的fetch.then.then…拆开,按同步的方式编写
内部的异步请求,使用 await 进行描述

HTML代码示范:

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>异步请求: fetch api</title>
  8. </head>
  9. <body>
  10. <button onclick="getUser(this)">Fetch API</button>
  11. <script>
  12. // function 前添加 async , 转为异步函数
  13. async function getUser() {
  14. let url = 'http://site.io/data.php?id=1';
  15. // 1. 等待结果再进行下一步操作,返回响应对象
  16. const response = await fetch(url);
  17. // 2. 将响应结果,转为json, json()
  18. const result = await response.json();
  19. console.log(result);
  20. }
  21. </script>
  22. </body>
  23. </html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post