优化之前
<script>
function reqBaidu() {
return fetch("https://jsonplaceholder.typicode.com/posts/1");
}
async function d1() {
console.log("d1")
await reqBaidu();
}
async function d2() {
console.log("d2")
await d1();
}
async function d3() {
console.log("d3")
const data = await d2();
console.log(data);
}
d3();
</script>
优化之前我们会发现,我有一个fetch请求返回promise,我要获取和数据我就得 用await ,用了await 当前函数必须是个async 如此循环往复调用,接下来所有的方法都要加上 async await,这就叫 异步传染性,我们可以用react 父组件加载子组件的原理
优化之后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function reqBaidu() {
return fetch("https://jsonplaceholder.typicode.com/posts/1");
}
function doReq() {
console.log("doReq")
let data = reqBaidu();
console.log(data);
}
waitAsync(doReq);
// 自定义 fetch 消除 异步传染性
function waitAsync(func) {
const cache = {
data: null,
status: 'pending',
};
//缓存旧的fetch
window.oldFetch = window.fetch;
// 重写fetch
function newFetch(url) {
if (cache.status === 'fulfilled') {
return cache.data;
} else if (cache.status === 'rejected') {
throw cache.data;
}
throw window.oldFetch(url).then(res => {
// // 检查网络请求是否成功
if (!res.ok) {
throw new Error('网络请求失败');
}
return res.json();
}).then(res => {
// 使用json()方法解析响应数据
cache.data = res;
cache.status = 'fulfilled';
}).catch(err => {
cache.data = err;
cache.status = 'rejected';
});
}
window.fetch = newFetch;
try {
// 执行函数
func();
} catch (err) {
if (err instanceof Promise) {
err.finally(() => {
window.fetch = newFetch;
func();
window.fetch = window.oldFetch;
});
}
}
window.fetch = window.oldFetch;
}
</script>
</body>
</html>