我正在尝试将我的API调用从使用jQuery ajax迁移到使用Fetch API。
我之前使用了jQuery ajaxStart和ajaxStop来在服务器调用期间显示加载图标。
现在我运行了几个并行的服务器请求,我希望当第一个请求开始时启动加载图标,并在最后一个请求完成后停止加载图标。
使用jQuery非常简单。然而,我无法找到使用Fetch API类似的技术。有任何想法吗?
我正在尝试将我的API调用从使用jQuery ajax迁移到使用Fetch API。
我之前使用了jQuery ajaxStart和ajaxStop来在服务器调用期间显示加载图标。
现在我运行了几个并行的服务器请求,我希望当第一个请求开始时启动加载图标,并在最后一个请求完成后停止加载图标。
使用jQuery非常简单。然而,我无法找到使用Fetch API类似的技术。有任何想法吗?
在调用fetch
之前启动您的旋转器,然后在finally
中停止它。
state.showSpinner = true;
Promise.all([fetch(url1), fetch(url2)])
.then(success => console.log(success))
.catch(error => console.error(error))
.finally(() => state.showSpinner = false);
Promise
来通知 fetch
被调用并完成。var params = {
a: 1,
b: 2
};
var data = new FormData();
data.append("json", JSON.stringify(params));
var currentRequest = new Request("/echo/json/", {
method: "POST",
body: data
});
var start, complete;
var fetchStart = new Promise(function(_start) {
start = _start;
})
var fetchComplete = new Promise(function(_complete) {
complete = _complete;
});
// do stuff when `fetch` is called
fetchStart.then(function(startData) {
console.log(startData)
});
// do stuff when `fetch` completes
fetchComplete.then(function(completeData) {
console.log(completeData)
});
var request = fetch(currentRequest);
[request, start({
"fetchStarted": currentRequest
})].shift()
.then(function(res) {
if (res.ok) {
// resolve `fetchComplete` `Promise` when `fetch` completes
complete({
"fetchCompleted": res
})
};
return res.json();
})
.then(function(data) {
document.body.textContent = JSON.stringify(data)
})
.catch(function(err) {
// if error, pass error to `fetchComplete`
complete({
"fetchCompleted": res,
"error": err
});
});
jsfiddle https://jsfiddle.net/abbpbah4/18/
的内容与编程有关。另请参阅{{link1:Fetch:POST json数据}}