简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM