Is There A Beforesend Javascript Promise?
I am using a script to send data to google drive. The script has two functions to detect when the request was sent or not. Is there a function alternative to jquery beforesend? To
Solution 1:
No there's not, but you can wrap it in your own function that you use everywhere.
functionmyFetch() {
console.log('about to send');
return fetch.apply(this, arguments);
}
myFetch('/echo').then(e =>console.log(e));
Solution 2:
There is no native way to have hooks on calls to window.fetch
. You could create a minimal wrapper class that executes that call for you, and allow you to pass before-send hooks to it that it will execute in advance:
//-----------------------------------------------------------// Implementation://-----------------------------------------------------------classCustomFetch {
constructor(url, init = {}) {
this.url = url;
this.init = init;
this.promise = null;
this.beforeSends = [];
}
/**
* Runs the actual fetch call.
* @return {Promise<Response>}
*/fetch() {
this._runBeforeSends();
this.promise = fetch(this.url, this.init);
returnthis.promise;
}
/**
* Runs all registered before-send functions
*/_runBeforeSends() {
this.beforeSends.forEach(fn =>fn(this));
returnthis;
}
/**
* Register a beforesend handler.
* @param {function(url, init): void} fn
*/beforeSend(fn) {
this.beforeSends.push(fn);
returnthis;
}
}
//-----------------------------------------------------------// Usage example://-----------------------------------------------------------// Create a special fetch wrapper with pre-defined arguments for 'Actual fetch':const postFetch = newCustomFetch('https://jsonplaceholder.typicode.com/posts/1');
// Register a before-send handler:
postFetch.beforeSend((fetch) => {
console.log(`About to send to ${fetch.url}`);
});
// call the fetch() method and get back the Promise<Response>// of the native fetch call:const posP = postFetch.fetch();
// When loaded, log the response data
posP.then((res) => res.json()).then(console.log);
This is a little more verbose than a simple function wrapper, but also gives you the advantage of being able to re-use a CustomFetch
instance – you can keep calling someFetch.fetch()
, and it will in turn keep calling the registered before-send handlers before proceeding with calling window.fetch
.
Post a Comment for "Is There A Beforesend Javascript Promise?"