For a more in-depth exploration of asynchronous code in JavaScript, check out:
- Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
- How do I return the response from an asynchronous call?
It's logging an empty string. Why is that?
This occurs because you initialized contentHtml = '';
. At the time you use console.log(contentHtml);
, it remains unchanged.
How should I properly assign a value to the variable contentHtml
?
The current method of assigning a value to contentHtml
works perfectly fine.
Your challenge doesn't lie in correctly assigning a value to contentHtml
. Rather, it pertains to your grasp on asynchronous programming flow.
JavaScript often employs anonymous functions defined inline where they are needed. Though this makes the code compact, it can sometimes hinder newer programmers' understanding of the program's execution flow when asynchronous operations are involved.
I've rewritten your code for better clarity on its sequence of operations:
var tabs = require("sdk/tabs");
var contentHtml = '';
function workerAttachedToTabWhenTabActivated() {
//Executed each time a tab is activated.
//Execution waits until activation.
self.port.emit("html", document.body.innerHTML);
}
function receiveHtmlMessageFromWorkerViaPortOn(message) {
//Only executed upon receiving a message named "html" via port.on.
//This part waits until the specific message arrives.
//Here we set contentHtml to message. However, since the rest of the program
//has already executed by this point, setting it here doesn't have any immediate impact.
contentHtml = message;
//Validating the setting of contentHtml.
console.log("contentHtml after receiving html message:" + contentHtml);
}
tabs.on('activate', function(tab) {
var worker = tab.attach({
contentScript: 'workerAttachedToTabWhenTabActivated();'
});
worker.port.on("html", receiveHtmlMessageFromWorkerViaPortOn(message))
});
//Upon reaching this statement, contentHtml remains "".
//Although listeners were configured for tab activation, no actual tab switch occurred at this moment.
console.log("contentHtml after setting up tab.attach:" + contentHtml);
As you can observe, setting the global variable contentHtml
to the message
lacks direct impact here as execution has progressed past the line
console.log("contentHtml after setting up tab.attach:" + contentHtml);
when the assignment takes place. This action would be more useful if there were additional asynchronous processes later on requiring knowledge of the most recent received html
message
.
In general, any dependencies on the html
message
's contents should be confined within the function handling the message reception.