1

I want to get a value from chrome.storage.local

var storage = chrome.storage.local;
authToken = storage.get('logintoken', function(result) {
    var channels = result.logintoken;
    authToken=result.logintoken;
    console.log(authToken);
   return authToken;
});
alert(authToken);

but out of the function authToken is undefined.

Erfan pj
  • 381
  • 1
  • 9
  • yes - `result` is only available in the callback `function(result) {` as, apparently, storage.get is asynchronous – Jaromanda X Sep 24 '22 at 08:08
  • so how can I use the result ?@JaromandaX – Erfan pj Sep 24 '22 at 08:10
  • inside the callback of course - or you could make it work more like browser.storage.local.get in firefox addons, which return a Promise - then you can use `await`, which inside an `async` function can look more synchronous ... emphasis on *look*, it won't be synchronous, but the code is easier to write for those that don't understand asynchrony – Jaromanda X Sep 24 '22 at 08:10

1 Answers1

0
function getAllStorageSyncData(top_key) {
    // Immediately return a promise and start asynchronous work
    return new Promise((resolve, reject) => {
        // Asynchronously fetch all data from storage.sync.
        chrome.storage.local.get(top_key, (items) => {
            // Pass any observed errors down the promise chain.
            if (chrome.runtime.lastError) {
                return reject(chrome.runtime.lastError);
            }
            // Pass the data retrieved from storage down the promise chain.
            resolve(items);
        });
    });
}

Used this method and await like

 var obj = await getAllStorageSyncData(['logintoken']);

and its worked https://stackoverflow.com/a/72947864/1615818

Erfan pj
  • 381
  • 1
  • 9