
3

【笔记】Fetch学习笔记
source link: https://en.loli.fj.cn/2022/11/26/Fetch%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Fetch学习笔记
通过Fetch的学习,引出async
、await
语法的学习
发送Get请求
- 如果需要携带参数,只需要在地址末尾拼接
?key=value&key=value
即可
<url>
:请求地址response.ok
:返回一个布尔值,表示请求是否成功response.status
:返回状态码数字response.statusText
:返回状态码文本response.url
:返回请求的地址
fetch("<url>")
.then((response) => {
return response.json();
})
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
...
});
异步函数写法
async
关键字必须配合await
关键字来使用,在使用await
关键字时,要将父级函数使用async
关键字修饰await
关键字只能修饰异步函数,被await
修饰的函数会在异步操作结束之后才会继续执行后面的代码
async function func() {
let response = await fetch("<url>");
let result = await response.json();
console.log(result);
}
func();
多个异步函数
- 如果执行多个异步操作,可以将所有需要执行的操作一同放到
Promise
中,再用await
执行
async function func() {
let promise1 = fetch("<url>");
let promise2 = fetch("<url>");
const [response1, response2] = await Promise.all(promise1, promise2);
console.log(response1.json());
console.log(response2.json());
}
func();
- 执行多个异步函数时不能使用
forEach
进行循环,而应当使用for
循环 - 所以如果执行多个异步操作,也可以使用
for await
进行循环
async function func() {
const promises = [
func1(),
func2()
]
for await (let promise in promises) {
...
}
}
func()
发送Post以及其他请求
method
:指定请求方式
get
:缺省值,Get请求post
:Post请求
headers
:指定请求头参数body
:指定请求体参数
fetch("<url>", {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"key": "value"
})
})
.then()
.then();
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK