【问题标题】:Is there a beforesend Javascript promise?是否有预先发送的 Javascript 承诺?
【发布时间】:2018-06-06 00:25:28
【问题描述】:

我正在使用脚本将数据发送到谷歌驱动器。该脚本有两个函数来检测请求何时发送。是否有替代 jquery beforesend 的功能?

检测请求正在发送?

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

【问题讨论】:

  • 只需在触发beforesend 事件时包装对您的 fetch 函数的每次调用?
  • 对不起,我不明白该怎么做。
  • 见baao回答中的第二个例子
  • 现在只有它一个

标签: javascript jquery promise


【解决方案1】:

不,没有,但您可以将其包装在您自己的函数中,以便在任何地方使用。

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

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

【讨论】:

  • 我不建议覆盖全局 fetch 变量,而只是封装在一个您可以在任何地方使用的自定义函数中。
  • 谢谢@bergi,有道理。我已经添加了。
【解决方案2】:

没有本地方法可以挂钩对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 之前注册了发送前处理程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2014-07-05
    • 2015-10-24
    • 2015-03-02
    • 2014-11-24
    相关资源
    最近更新 更多