前端Fetch API接收数据
Fetch API
Fetch API 可以用来获取远程数据,它有两种方式接收结果,同步方式与异步方式
格式
fetch(url, options) // 返回 Promise
同步方式
const 结果 = await Promise
// 后续代码
- await 关键字必须在一个标记了 async 的 function 内来使用
- 后续代码在结果返回后执行
异步方式
Promise
.then(结果 => { ... })
// 后续代码
- 后续代码不必等待结果返回就可以执行
例:
在 express 服务器上有 students.json 文件
[
{ "id": 1, "name": "张三", "sex": "男", "age": 18 },
{ "id": 2, "name": "李四", "sex": "女", "age": 17 }
]
现在用 fetch api 获取这些数据,并展示
同步方式
<script>
async function findStudents() {
try {
// 获取响应对象
const resp = await fetch('students.json')
// 获取响应体, 按json格式转换为js数组
const array = await resp.json();
// 显示数据
const tp = document.getElementById("tp");
const row = tp.content;
const [c1,c2,c3,c4] = row.querySelectorAll(".col");
const tbody = document.querySelector('.tbody');
for(const {id,name,sex,age} of array) {
c1.textContent = id;
c2.textContent = name;
c3.textContent = sex;
c4.textContent = age;
// 复制元素
const newRow = document.importNode(row, true);
// 建立父子关系
tbody.appendChild(newRow);
}
} catch (e) {
console.log(e);
}
}
findStudents()
</script>
- fetch(‘students.json’) 内部会发送请求,但响应结果不能立刻返回,因此 await 就是等待响应结果返回
- 其中 resp.json() 也不是立刻能返回结果,它返回的也是 Promise 对象,也要配合 await 取结果
异步方式
<script>
fetch('students.json')
.then( resp => resp.json() )
.then( array => {
// 显示数据
const tp = document.getElementById("tp");
const row = tp.content;
const [c1,c2,c3,c4] = row.querySelectorAll(".col");
const tbody = document.querySelector('.tbody');
for(const {id,name,sex,age} of array) {
c1.textContent = id;
c2.textContent = name;
c3.textContent = sex;
c4.textContent = age;
// 复制元素
const newRow = document.importNode(row, true);
// 建立父子关系
tbody.appendChild(newRow);
}
})
.catch( e => console.log(e) )
</script>
- 第一个 then 是在响应返回后,才会调用它里面的箭头函数,箭头函数参数即 resp 响应对象
- 第二个 then 是在 json 解析完成后,才会调用它里面的箭头函数,箭头函数参数即解析结果(本例是 array 数组)
- 上一个 then 返回的是 Promise 对象时,才能链式调用下一个 then