I'm writing a firefox addon and I want to do something before every http request is issued. Pseudocode:
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
}
}
The problem is that asyncFunction2() may finishes after observe() finished. And according to Firefox, the request will be issued after observe() finished. Thus when asyncFunction2() is editing httpChannel, the variable 'httpChannel' is already out of date(because observe() ends).
To keep the request not issued before asyncFunction2() finished, I need to do sth to let the main thread wait for asyncFunction2() at point 1. I have tried to put 'setTimeout(function waitfor(){},xxxx)' at point 1, but waitfor() starts after observe() ends. I also tried to put asyncFunction1&2 in a chrome workder(similar to web worker) and let the worker thread sends a message when asyncFunction2 finished. However, javascript seems unable to be interrupted when executing the main thread. What i found is that javascript only put the 'receive a message ! event' into the task queue. Thus when javascript is dealing with the message, the observe() has already returned.