如何让javascript主线程休眠?

如何让javascript主线程休眠?,javascript,multithreading,firefox,firefox-addon,Javascript,Multithreading,Firefox,Firefox Addon,我正在编写一个firefox插件,我想在发出每个http请求之前做点什么。伪代码: observerService.addObserver(httpRequestObserver, "http-on-modify-request", false); var httpRequestObserver= { observe: function() { var httpChannel = subject.QueryInterface(Ci.nsIHttpChann

我正在编写一个firefox插件,我想在发出每个http请求之前做点什么。伪代码:

observerService.addObserver(httpRequestObserver, "http-on-modify-request", false);
var httpRequestObserver=
{
    observe: function()
    {
            var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);

            asyncFunction1(){
                // asynchronous function No.1
            }.then(asyncFunction2(){
                // asynchronous function No.2, this function will be called after asyncFunction1 finished
                // do something to httpChannel (edit the request header etc.)
            });
        //point 1
    }
}
问题是asyncFunction2可能在观察完成后完成。根据Firefox,请求将在完成后发出。因此,当asyncFunction2编辑httpChannel时,变量“httpChannel”已经过期,因为observe结束


为了使请求在asyncFunction2完成之前不会发出,我需要做一些事情,让主线程在第1点等待asyncFunction2。我曾尝试将“setTimeoutfunction waitfor{},xxxx”放在第1点,但waitfor在观察结束后启动。我还尝试将asyncFunction1和asyncFunction2放在与web worker类似的chrome worker中,并让worker线程在asyncFunction2完成时发送消息。但是,在执行主线程时,javascript似乎无法被中断。我发现javascript只放了“接收消息!事件“”进入任务队列。因此,当javascript处理消息时,observe已经返回。

因此,当asyncFunction2编辑httpChannel时,变量“httpChannel”已经过期,因为observe结束了,但是即使在observe函数结束后,变量httpChannel也可以在asyncFunction2中访问。尽管它所引用的对象可能不活动,但在您的上下文中无论这意味着什么。httpChannel确实可以在asyncFunction2中访问,但是编辑httpChannel没有意义,因为请求的对象已经发出。请参阅如何将其作为新请求重新发出,这将允许您稍微暂停它