ajaxStart和ajaxStop等同于fetch API
ajaxStart and ajaxStop equivalent with fetch API
我正在尝试将API调用从使用jQueryajax迁移到使用Fetch API。
我使用jQuery ajaxStart和ajaxStop在服务器调用期间显示加载微调器。
我正在运行几个并行服务器请求,我希望微调器在第一个请求启动时启动,在最后一个请求解决时停止。
与jQuery相比,这是非常直接的。然而,我找不到使用fetch API的类似技术。有什么想法吗?
当调用fetch
并完成时,可以使用Promise
进行通知
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
});
});
jsfiddlehttps://jsfiddle.net/abbpbah4/18/
另请参阅Fetch:POST json数据
只需在调用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);
相关文章:
- IE11中的第二个调用取消了第一个Fetch API调用
- ajaxStart和ajaxStop等同于fetch API
- Fetch Api无法从PHP服务器获取会话
- Javascript fetch API in react-flux
- JavaScript 的 Fetch API 的“同源”和“no-cors”有什么区别?
- Fetch API and Cordova
- 预检请求失败,并显示 window.fetch api
- JS Fetch api and Symfony2 FOSRestBundle
- Azure Applications Insights节点js模块不工作- Fetch API无法加载错误
- 如何使用模式'no-cors'的fetch API获取数据
- 在fetch api调用时未设置标头
- 在ReactNative应用程序中使用fetch API忽略自签名SSL证书的错误
- Babel将新的Request (fetch-api)转换为函数调用,导致Chrome出现错误
- Fetch API post永远不会落入.then
- 如何将Fetch API的值传递给变量
- Javascript中的Fetch API返回[object, object]
- POST Request with Fetch API?
- 将变量从JavaScript传递到php(通过fetch api)
- JS -获取文本或JSON与Fetch API
- Typescript函数中的`Fetch` API