文章内容

2022/10/10 21:52:28,作 者: 黄兵

JavaScript fetch 理解

下面是 fetch() 的解释:

全局的 fetch() 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response 对象。

下面是一个示例代码:

const request = new Request("/progress/" + thread);
fetch(request, fetchInit).then(function (response) {
return response.json();
}).then(function (response) {
const progress = parseInt(response.progress);
circularProgress.foundation.setProgress(progress / 100);
if (progress === 100) {
// 进度完成,清除定时器
clearInterval(interval);
// 关闭进度
circularProgress.foundation.close();
document.querySelector('.mdc-button').disabled = false;
const btnLabelEle = document.querySelector(".label-wrapper");
btnLabelEle.style.display = 'block';
document.querySelectorAll(".query-result-container").forEach(el => {
el.style.display = "block";
});
}
});

同时我们可以这样写,init 对象中的 headers 也可以是一个对象字面量

function download_progress() {
const fetchInit = {
method: 'GET',
headers: {'Content-Type': 'application/json'},
};
const request = new Request("/progress/" + thread);
fetch(request, fetchInit).then(function (response) {
return response.json();
}).then(function (response) {
const progress = parseInt(response.progress);
circularProgress.foundation.setProgress(progress / 100);
if (progress === 100) {
// 进度完成,清除定时器
clearInterval(interval);
// 关闭进度
circularProgress.foundation.close();
document.querySelector('.mdc-button').disabled = false;
const btnLabelEle = document.querySelector(".label-wrapper");
btnLabelEle.style.display = 'block';
document.querySelectorAll(".query-result-container").forEach(el => {
el.style.display = "block";
});
}
});
}

最后需要说明的是:这里我们直接使用 response.json()response 数据转换成 json 数据。


参考资料:

1、fetch()

2、Response.json()


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - JavaScript fetch 理解

分享到:

发表评论

评论列表