是否有一个之前的Javascript承诺?

时间:2018-06-05 15:43:00

标签: javascript jquery promise

我正在使用脚本将数据发送到Google云端硬盘。该脚本有两个功能来检测请求的发送时间。是否有替代jquery beforesend的函数?

要检测请求正在发送?

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

2 个答案:

答案 0 :(得分:1)

不,没有,但你可以把它包装在你自己的功能中,你到处使用它。

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

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

答案 1 :(得分:0)

window.fetch的调用没有本地方法可以挂钩。您可以创建一个为您执行该调用的最小包装类,并允许您将 before-send 挂钩传递给它,它将提前执行​​:

//-----------------------------------------------------------
// 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.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);

这比简单的函数包装器更冗长,但也为您提供了重用CustomFetch实例的优势 - 您可以继续调用someFetch.fetch(),它会在在继续调用window.fetch之前,请继续调用已注册的发送前处理程序。