有一个beforesend的Javascript promise吗?

3
我正在使用脚本将数据发送到谷歌云端硬盘。该脚本有两个函数用于检测请求是否已发送。是否存在一种功能替代jquery的beforesend?
用于检测请求是否正在发送?
fetch(scriptURL, { method: 'POST', body: new FormData(form)})  
         .then((response) => {
               alertify.success("Sent succesfully");
            })
             .catch((err) => {
                alertify.error("Failed to send");
            });

只需在调用fetch函数时包装一个“beforesend”事件即可? - Bergi
抱歉,我不知道如何做这个。 - user9402741
请看baao答案中的第二个示例。 - Bergi
现在它是唯一的一个。 - baao
2个回答

4
没有,但您可以将其包装在您自己的函数中,并在任何地方使用该函数。
function myFetch() {
    console.log('about to send');
    return fetch.apply(this, arguments);
}

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

2
我不建议覆盖全局的 fetch 变量,而是应该在一个自定义函数中进行包装,并在需要时随处使用。 - Bergi
谢谢@bergi,很有道理。我已经添加了。 - baao

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接