3

【笔记】Fetch学习笔记

 1 year ago
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.
neoserver,ios ssh client

Fetch学习笔记
通过Fetch的学习,引出asyncawait语法的学习

发送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();

哔哩哔哩——黑马前端教程
哔哩哔哩——奇乐编程学院


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK