You don't. Because you can't do mutex-style synchronization.
JavaScript is single-threaded. Imagine the following code:
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
while(typeof val == undefined) {}
sendResponse(val);//val will be send back after val assigned
});
It seems like it will loop until the assignment happens; however, in practice it is guaranteed to loop forever if it enters the loop. JS processes things with a queue, and you just made sure the current task never ends.
So you will need to relinquish control one way or another.
Just reply that you don't have an answer yet!
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse) {
if(typeof val == undefined) {
sendResponse(); // check for undefined on the other side
} else {
sendResponse(val);
}
});
Then adjust the logic on the receiving end.
But that might not be a good solution. In that case..
Delay the response, by queuing the requests. Chrome allows you to use sendResponse
asynchronously, but you have to indicate that:
This function [sendResponse
] becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse
is called).
So this might be something like this:
var requests = [];
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse) {
if(typeof val == undefined) {
requests.push(sendResponse);
return true;
} else {
sendResponse(val);
}
});
/* ... */
val = theActualValue;
for(callback of requests) callback(val);
requests = [];