Why the global variable is not set immediately after defining the callback / listen function (asynchronous messaging, port.on)

I am very new to writing Firefox add-ons. But I try my best. So, I have this code that I got from MDN :

var tabs = require("sdk/tabs");

tabs.on('activate', function(tab) {
  var worker = tab.attach({
    contentScript: 'self.port.emit("html", document.body.innerHTML);'
  });
  worker.port.on("html", function(message) {
   console.log(message)
  })
});

When I change it to:

var contentHtml = '';

var tabs = require("sdk/tabs");

tabs.on('activate', function(tab) {
  var worker = tab.attach({
    contentScript: 'self.port.emit("html", document.body.innerHTML);'
  });
  worker.port.on("html", function(message) {
    contentHtml = message
  })
});

console.log(contentHtml);

He writes an empty string. Why is this?

What is the correct way to put this in a variable contentHtml?

+1
source share
1 answer

For more information on asynchronous code in JavaScript, see below:

. ?

contentHtml = '';. , console.log(contentHtml);, .

contentHtml?

, , contentHtml .

, contentHtml. , Firefox. .

JavaScript , , . , , , , , .

, , , :

var tabs = require("sdk/tabs");
var contentHtml = '';

function workerAttachedToTabWhenTabActivated() {
    //This is executed every time a tab is activated.
    //It is not executed until that time.
    self.port.emit("html", document.body.innerHTML);
}

function receiveHtmlMessageFromWorkerViaPortOn(message) {
    //This is executed only when we receive a message via port.on that is named "html".
    //It is not executed until such a message is received.

    //We set contentHtml to message here. While the contentHtml variable is defined in the
    //  containing code, setting it here does not, currently, do us any good because
    //  the rest of the program has already completed by the time this is executed.
    contentHtml = message;

    //Show that we actualy do set 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))
});

//When we execute the following statement contentHtml is still "".
//When we get here, we have set up our functions that are executed upon a tab becoming
//active, but that code has not yet been executed because no tab became active in the small
//amount of time between setting up those listeners and this executing.
console.log("contentHtml after setting up tab.attach:" + contentHtml);

, contentHtml message ,

console.log("contentHtml after setting up tab.attach:" + contentHtml);

contentHtml message. contentHtml message , , , , html message, .

, , html message, , .

+1

Source: https://habr.com/ru/post/1652984/


All Articles