ajaxStart和ajaxStop等同于fetch API

ajaxStart and ajaxStop equivalent with fetch API

本文关键字:fetch API 等同于 ajaxStop ajaxStart      更新时间:2023-09-26

我正在尝试将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);