0

While developing a chrome extension I used the following code in my background script:

session="abcd";
chrome.storage.sync.set({"session": session}, function () {
    console.log("session set as: " + session)
});

chrome.storage.sync.get(["session"], ({data}) => {
    console.log("session retrieved as: " + data.key)
});

The second function returns undefined. From my searches it appears that I am making some mistake while calling async function. But I am not able to identify it. How to write this code correctly?

Tarun Khare
  • 1,447
  • 6
  • 25
  • 43
  • are you talking about localStorage in browser? – nima Apr 21 '19 at 19:03
  • No, its about chrome storage api used in extension development. – Tarun Khare Apr 21 '19 at 19:04
  • what happens if you don't destructure the parameter? – Daniel A. White Apr 21 '19 at 19:21
  • 1. the API is asynchronous so `get` can run before `set` is finished, the async code should be written by chaining callbacks or using Promise wrappers (optionally with async/await syntax), 2. instead of `({data})` which is an incorrect destructuring (there's no `data` inside the callback parameter and there's also no `key` in `data`) you need `({session})` since this is what you're reading - the value will be inside a **local** variable named `session` that will be **shadowing** your other global `session` so you may want to avoid destructuring. – wOxxOm Apr 21 '19 at 19:35
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Josh Lee Apr 22 '19 at 03:39

1 Answers1

0

CHROME.STORAGE.SYNC.SET/GET are asynchronous functions and thus GET should be in the callback otherwise session might be undefined.

This works fine.

session="abcd";

chrome.storage.sync.set({"session": session}, function () {
    console.log("session set as: " + session)
    chrome.storage.sync.get("session", functions(data) => {
        console.log("session retrieved as: " + data["session"])
    });
});