admin管理员组

文章数量:1399155

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 detect that the request is being sending?

fetch(scriptURL, { method: 'POST', body: new FormData(form)})  
         .then((response) => {
               alertify.success("Sent succesfully");
            })
             .catch((err) => {
                alertify.error("Failed to send");
            });

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 detect that the request is being sending?

fetch(scriptURL, { method: 'POST', body: new FormData(form)})  
         .then((response) => {
               alertify.success("Sent succesfully");
            })
             .catch((err) => {
                alertify.error("Failed to send");
            });
Share Improve this question asked Jun 5, 2018 at 15:42 user9402741user9402741 4
  • Just wrap every call to your fetch function in firing a beforesend event? – Bergi Commented Jun 5, 2018 at 15:57
  • sorry i don't understand how to do this. – user9402741 Commented Jun 5, 2018 at 16:00
  • See the second example in baao's answer – Bergi Commented Jun 5, 2018 at 16:01
  • Now it's the only one – baao Commented Jun 5, 2018 at 16:02
Add a ment  | 

2 Answers 2

Reset to default 4

No there's not, but you can wrap it in your own function that you use everywhere.

function myFetch() {
    console.log('about to send');
    return fetch.apply(this, arguments);
}

 myFetch('/echo').then(e => console.log(e));

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:
//-----------------------------------------------------------

class CustomFetch {

    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);
        return this.promise;
    }

    /**
     * Runs all registered before-send functions
     */
    _runBeforeSends() {
        this.beforeSends.forEach(fn => fn(this));
        return this;
    }

    /**
     * Register a beforesend handler.
     * @param {function(url, init): void} fn
     */
    beforeSend(fn) {
        this.beforeSends.push(fn);
        return this;
    }
}

//-----------------------------------------------------------
// Usage example:
//-----------------------------------------------------------

// Create a special fetch wrapper with pre-defined arguments for 'Actual fetch':
const postFetch = new CustomFetch('https://jsonplaceholder.typicode./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.

本文标签: jqueryIs there a beforesend Javascript promiseStack Overflow