I am trying to create a Firefox add-on that performs a simple action from a context menu. This add-on works by displaying an item when right-clicked with a string selected, and executing the process when the item is clicked.
In Javascript in Firefox Add-On, when XX.then is executed after browser.storage.sync.get is executed, execution moves to the next line even though the function specified in XX.then has not finished processing.
How can I make sure that a given function is completely processed before moving on to the next line of execution?
As an example, a string "A" is stored in the item "optiondata" in the storage.
browser.contextMenus.create({
id: "mycontextmenu",
title: "mycontextmenu",
contexts: ["selection"]
});
browser.contextMenus.onClicked.addListener(function(info,tab){
if (info.menuItemId == "mycontextmenu"){
var storeddata;
function onError(error) {
console.log(`Error: ${error}`);
}
function readData(result) {
storeddata = result.optiondata;
}
var getting = browser.storage.sync.get("optiondata");
getting.then(readData, onError);
console.log(storeddata);
}
});
I was going to be able to first read the contents in the optiondata from storage and then display that retrieved content in the console.log in the last line.
However, the log only showed "undefined".
To see in which order each line was executed, I changed the code as follows:
browser.contextMenus.create({
id: "mycontextmenu",
title: "mycontextmenu",
contexts: ["selection"]
});
browser.contextMenus.onClicked.addListener(function(info,tab){
if (info.menuItemId == "mycontextmenu"){
console.log("1");
var storeddata;
function onError(error) {
console.log(`Error: ${error}`);
}
function readData(result) {
console.log("2");
storeddata = result.optiondata;
}
var getting = browser.storage.sync.get("optiondata");
getting.then(readData, onError);
console.log("3");
console.log(storeddata);
}
});
I expected the numbers 1, 2, and 3 to appear in the log in the correct order, with the contents of console.log(storeddata), "A" appearing last. However, the results differed and were as follows:
1
3
undefined
2
It appears that execution has moved to the next line of "getting.then" before the processing of the first function specified in "getting.then" ("readData" in this case) is completed. How can I make the "readData" function finish processing before moving on to the next line of "getting.then"?