Mike M
Mike M

Reputation: 752

Retrieving data from localStorage

I'm trying to retrieve a string from localStorage which is working, but I'm not sure of the order of execution. Or maybe I'm missing something.

//content_script.js

function getSize(){
    chrome.extension.sendMessage({method: "getSize"}, function(response){
        size = response.sizeIs; 
    });
    alert(size);
    return size;
}

and

//background.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSize")
        sendResponse({sizeIs: localStorage['size']});
});

The alert messages are:

undefined
Large

respectively.

So I guess my question is, why is the variable working inside the sendMessage function, but not outside?

Upvotes: 1

Views: 94

Answers (1)

Oleg
Oleg

Reputation: 23307

It's because in your example alert(size); executes before size = response.sizeIs;

It should be like this:

function getSize(callback){
  chrome.extension.sendMessage({method: "getSize"}, function(response){
    size = response.sizeIs; 
    callback(size);
  });
}

And call it this way:

getSize(function(size) {
  alert(size);
});

instead of:

size = getSize();
alert(size);

chrome.extension.sendMessage is asynchronous (non-blocking) method which means that you can't get result immediatelly. You have to pass a callback function and handle result inside

It's like setTimeout function. Try to execute the following code:

setTimeout(function() {
  console.log('test 1');
}, 100);
console.log('test 2');

and you will get in your console:

test 2
test 1

In the case test 2 showed immediatelly and test 1 - after 100ms. This is how asynchronous functions/methods work

Here you can read more about asynchronous functions

Upvotes: 1

Related Questions