Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有提前发送Javascript的承诺?_Javascript_Jquery_Promise - Fatal编程技术网

是否有提前发送Javascript的承诺?

是否有提前发送Javascript的承诺?,javascript,jquery,promise,Javascript,Jquery,Promise,我正在使用脚本将数据发送到google drive。该脚本有两个功能来检测何时发送请求。在发送之前是否有jquery的替代函数 要检测请求是否正在发送 fetch(scriptURL, { method: 'POST', body: new FormData(form)}) .then((response) => { alertify.success("Sent succesfully"); })

我正在使用脚本将数据发送到google drive。该脚本有两个功能来检测何时发送请求。在发送之前是否有jquery的替代函数

要检测请求是否正在发送

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

没有,但是你可以把它包装在你自己的函数中,你可以在任何地方使用它

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

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

在调用
window.fetch
时,没有本机的钩子方法。您可以创建一个最小的包装器类来执行该调用,并允许您在向其发送钩子之前传递它将提前执行的钩子:

//-----------------------------------------------------------
//实施:
//-----------------------------------------------------------
类CustomFetch{
构造函数(url,init={}){
this.url=url;
this.init=init;
this.promise=null;
this.beforeSends=[];
}
/**
*运行实际的获取调用。
*@return{Promise}
*/
fetch(){
这个;
this.promise=fetch(this.url,this.init);
归还这个。承诺;
}
/**
*运行所有在发送之前注册的函数
*/
_runBeforeSends(){
this.beforeSends.forEach(fn=>fn(this));
归还这个;
}
/**
*注册beforesend处理程序。
*@param{function(url,init):void}fn
*/
发送前(fn){
此。前发送。推送(fn);
归还这个;
}
}
//-----------------------------------------------------------
//用法示例:
//-----------------------------------------------------------
//使用“实际提取”的预定义参数创建特殊提取包装器:
const postFetch=new CustomFetch('https://jsonplaceholder.typicode.com/posts/1');
//在发送前注册处理程序:
postFetch.beforeSend((fetch)=>{
log(`About to send to${fetch.url}`);
});
//调用fetch()方法并获取承诺
//本机获取调用的名称:
const posP=postFetch.fetch();
//加载时,记录响应数据

posP.then((res)=>res.json()).then(console.log)只需在发送前触发一个
事件时包装对fetch函数的每次调用?很抱歉,我不知道怎么做。请参见baao回答中的第二个示例现在这是唯一一个我不建议覆盖全局
fetch
变量的调用,而只需包装在您随处使用的自定义函数中。谢谢@bergi,有道理。我已经补充了这一点。