Blogger Information
Blog 26
fans 0
comment 0
visits 11930
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示fetch/async/awaitp的用法(1115作业)
高空中的云
Original
427 people have browsed it

fetch

XMLHttpRequest的更理想的替代方案,用于在Javascript脚本里发出HTTP请求。

  1. - `fetch()`使用promise,不使用回调函数,因此大大简化了写法,更简洁
  2. - 模块化设计,API分散在多个对象上(Response对象,Request对象,Headers对象),更合理
  3. - 默认情况下,fetch不会从服务端发送或接收任何cookies,如果站点依赖于用户session,则会导致未经认证的请求(要发送cookies,必须设置credentials选项)
  4. - 通过数据流(Stream对象)处理数据,可以分块读取,有利于提高网站性能,减少内存占用,对于请求大文件或者网速慢的场景相当有用。
  5. - 只有网络错误,或者无法连接时,fetch()才会报错,其他情况都不会报错(即便服务器返回的是4XX5XX状态码)

基本用法如下,

  1. // Promise<Response> fetch(input[, init]);
  2. fetch(url)
  3. .then(...)
  4. .then(...)
  5. .catch(...)

例如,

  1. fetch('https://api.php.cn/index')
  2. .then(response => response.json())
  3. .then(json => console.log(json))
  4. .catch(err => console.log('Request Failed',err))

fetch()接收到的response是一个Stream对象,response.json()是一个异步操作,取出所有内容,并将其转为JSON对象。

  1. // 自定义post函数postData
  2. let param = {
  3. title: 'foo',
  4. body: 'bar',
  5. userId: 1,
  6. };
  7. let url = 'https://jsonplaceholder.typicode.com/posts';
  8. postData(url, param)
  9. .then((json) => console.log(json))
  10. .catch(error => console.error(error))
  11. function postData(url, data) {
  12. // Default options are marked with *
  13. return fetch(url, {
  14. body: JSON.stringify(data), // must match 'Content-Type' header
  15. cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  16. credentials: 'include', // include, same-origin, *omit
  17. headers: {
  18. 'Content-type': 'application/json; charset=UTF-8',
  19. },
  20. method: 'POST', // *GET, POST, PUT, DELETE, etc.
  21. mode: 'cors', // no-cors, cors, *same-origin
  22. redirect: 'follow', // manual, *follow, error
  23. referrer: 'no-referrer', // *client, no-referrer
  24. })
  25. .then(response => response.json()) // parses response to JSON
  26. }

async/await

是一种更舒适的方式使用promise的特殊语法,async确保了函数返回一个promise,也会将非promise值包装进去。在async函数实例中,允许使用await关键字。async和await关键字让我们可以用一种更简洁的方式写出基于Promise的异步行为,无需刻意的链式调用promise

  1. async function test(){
  2. let promise = new Promise((resolve,reject) => {
  3. setTimeout(() => resolve("Promise done!"), 1000)
  4. });
  5. let result = await promise; // await 表示等待promise这个异步函数结束后才会执行,如果不加await,则会按照顺序执行,把promise函数赋值给result,而不是“Promise done!"这个执行结果返回的字符串。
  6. alert(result)
  7. }
  8. test();

async/await适用场景:

  • 有多个请求,且请求之间有依赖顺序关系
  • 并发请求,提高请求效率
  • 错误处理
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:总结的不错, 继续加油
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!