Fetch

(fai 洗)

window 自带的发送请求的 API,类似 xhr

>>关注分离的设计思想,不是一下子不数据给你,

  • 先确认   是否联系服务器成功
  • 再获取数据
  • 联系成功后   数据放在 res.json() 这个 promise 对象中

>>特点

  • 原生函数,不再使用 XmlHttpRequest  对象提交 ajax 请求,Fetch 本身就是一个请求对象。
  • 老版本浏览器可能不支持

每个 then 中都要错误信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fetch(`/api1/search/users2?q=${keyWord}`)
.then(
(res) => {
console.log("联系服务器成功了", res);
/* res.json()就是一个promise对象 */
return res.json();
},
(err) => {
console.log("联系服务器失败了", err);
PubSub.publish("bzj", { isLoading: false, err: err.message });
/* 失败了 就初始化 promise状态 以防往下走 */
return new Promise(() => {});
}
)
.then(
(res) => {
console.log("获取数据成功:", res);
PubSub.publish("bzj", { isLoading: false, users: data.items });
},
(err) => {
console.log("获取数据失败了:", err);
PubSub.publish("bzj", { isLoading: false, err: err.message });
}
);

错误信息最后一起处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fetch(`/api1/search/users2?q=${keyWord}`)
.then((res) => {
console.log("联系服务器成功了", res);
/* res.json() 才是真的的数据 就是一个promise对象 */
return res.json();
})
.then((res) => {
console.log("获取数据成功:", res);
PubSub.publish("bzj", { isLoading: false, users: data.items });
})
.catch((err) => {
console.log("错误", err);
PubSub.publish("bzj", { isLoading: false, err: err.message });
});

async await  实现

1
2
3
4
5
6
7
try {
const res = await fetch(`/api1/search/users2?q=${keyWord}`);
const data = await res.json();
PubSub.publish("bzj", { isLoading: false, users: data.items });
} catch (err) {
PubSub.publish("bzj", { isLoading: false, err: err.message });
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!