AjaxStart and the equivalent of ajaxStop with the fetch API

I am trying to port my API calls using jQuery ajax to use the Fetch API.

I used jQuery ajaxStart and ajaxStop to display the load counter during server calls.

I am running several requests on a parallel server, I want the counter to start when the first request starts and stops when the last request is completed.

That was pretty frank with jQuery. However, I cannot find a similar technique using the fetch API. Any ideas?

+5
source share
1 answer

You can use Promise to notify when fetch is called and terminated.

 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/


See also Fetch: POST json data

+1
source

All Articles