批改状态:合格
老师批语:总结的不错, 继续加油
fetch
是XMLHttpRequest的更理想的替代方案,用于在Javascript脚本里发出HTTP请求。
- `fetch()`使用promise,不使用回调函数,因此大大简化了写法,更简洁- 模块化设计,API分散在多个对象上(Response对象,Request对象,Headers对象),更合理- 默认情况下,fetch不会从服务端发送或接收任何cookies,如果站点依赖于用户session,则会导致未经认证的请求(要发送cookies,必须设置credentials选项)- 通过数据流(Stream对象)处理数据,可以分块读取,有利于提高网站性能,减少内存占用,对于请求大文件或者网速慢的场景相当有用。- 只有网络错误,或者无法连接时,fetch()才会报错,其他情况都不会报错(即便服务器返回的是4XX或5XX状态码)
基本用法如下,
// Promise<Response> fetch(input[, init]);fetch(url).then(...).then(...).catch(...)
例如,
fetch('https://api.php.cn/index').then(response => response.json()).then(json => console.log(json)).catch(err => console.log('Request Failed',err))
fetch()接收到的response是一个Stream对象,response.json()是一个异步操作,取出所有内容,并将其转为JSON对象。
// 自定义post函数postDatalet param = {title: 'foo',body: 'bar',userId: 1,};let url = 'https://jsonplaceholder.typicode.com/posts';postData(url, param).then((json) => console.log(json)).catch(error => console.error(error))function postData(url, data) {// Default options are marked with *return fetch(url, {body: JSON.stringify(data), // must match 'Content-Type' headercache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cachedcredentials: 'include', // include, same-origin, *omitheaders: {'Content-type': 'application/json; charset=UTF-8',},method: 'POST', // *GET, POST, PUT, DELETE, etc.mode: 'cors', // no-cors, cors, *same-originredirect: 'follow', // manual, *follow, errorreferrer: 'no-referrer', // *client, no-referrer}).then(response => response.json()) // parses response to JSON}
async/await
是一种更舒适的方式使用promise的特殊语法,async确保了函数返回一个promise,也会将非promise值包装进去。在async函数实例中,允许使用await关键字。async和await关键字让我们可以用一种更简洁的方式写出基于Promise的异步行为,无需刻意的链式调用promise
async function test(){let promise = new Promise((resolve,reject) => {setTimeout(() => resolve("Promise done!"), 1000)});let result = await promise; // await 表示等待promise这个异步函数结束后才会执行,如果不加await,则会按照顺序执行,把promise函数赋值给result,而不是“Promise done!"这个执行结果返回的字符串。alert(result)}test();
async/await适用场景:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号