🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## Fetch `fetch()`是 XMLHttpRequest 的升级版 1. `fetch()`使用 Promise,不使用回调函数,因此大大简化了写法,写起来更简洁。 2. `fetch()`采用模块化设计,API 分散在多个对象上(Response 对象、Request 对象、Headers 对象),更合理一些;相比之下,XMLHttpRequest 的 API 设计并不是很好,输入、输出、状态都在同一个接口管理,容易写出非常混乱的代码。 3. `fetch()`通过数据流(Stream 对象)处理数据,可以分块读取,有利于提高网站性能表现,减少内存占用,对于请求大文件或者网速慢的场景相当有用。XMLHTTPRequest 对象不支持数据流,所有的数据必须放在缓存里,不支持分块读取,必须等待全部拿到后,再一次性吐出来。 ## 使用样式 ``` fetch('https://api.github.com/users/ruanyf') .then(response => { if (!response.ok) { throw new Error('Network response was not OK'); } return response.json() }) .then(json => console.log(json)) .catch(err => console.log('Request Failed', err)); ``` 使用 await 语法改写 ``` async function getJSON() { let url = 'https://api.github.com/users/ruanyf'; try { let response = await fetch(url); return await response.json(); } catch (error) { console.log('Request Failed', error); } } ``` `await`语句必须放在`try...catch`里面,这样才能捕捉异步操作中可能发生的错误