Todd
Todd

Reputation: 325

chrome local storage async pass data to callback properly

function func(data) {
    var data2 = {'apple', 'pear'};

    chrome.storage.local.get("key", function(items) {
        // Lots of code here that takes time.
        // use "data"
        // use "data2"
    }
}

1) How do I use "data" and "data2" from inside this callback? I'm just not sure how to pass that data into the callback properly. Do I create a global?

2) It seems like I can use them, but from what I understand, it's async, and I'm afraid func() will end before the callback is called and both data and data2 will go out of scope by that time, making them unusable. What is the proper way of doing this?

Upvotes: 1

Views: 143

Answers (2)

Xan
Xan

Reputation: 77523

You just use them.

By referencing them inside the callback you create a closure, so they will continue to exist after func has finished executing, until there are no references to them left.

However, it's important to make sure they don't change before the callback executes. In your case it's not a concern, but if they come from an outer scope you need to keep that in mind.

Upvotes: 0

Danny Delott
Danny Delott

Reputation: 6988

You'll retain access to the data and data2 variables through what's called the Closure Scope.

You don't have to do anything different. Just use the variables like normal.

Upvotes: 1

Related Questions