Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for asynchronous chrome.storage.local.get() to finish before continuing execution

I have two calls to chrome.storage.local.get(). I need for these calls to finish before continuing executing the rest of the code (calling continueCode() function) for my chrome extension, but I'm not sure how to do this, here is my code.

function getData() {
    chrome.storage.local.get(['key'], function(result) {
        if (Object.values(result)[0] != undefined) {
            object1.innerHTML = Object.values(result)[0].val;
        }
    });

    chrome.storage.local.get(['key2'], function(result) {
         if (Object.values(result)[0] != undefined) {
             object2.innerHTML = Object.values(result)[0].val;
         }
    });

    continueCode();
}
like image 925
nenur Avatar asked Feb 02 '26 01:02

nenur


2 Answers

You can use new Promise, async/await to handle this. Let's say that you want to handle chrome.storage.local.get synchronously so that continueCode() can has the needed data.

Get data:

  const readLocalStorage = async (key) => {
    return new Promise((resolve, reject) => {
      chrome.storage.local.get([key], function (result) {
        if (result[key] === undefined) {
          reject();
        } else {
          resolve(result[key]);
        }
      });
    });
  };

Main function:


async function getData() {
    let key1 = await readLocalStorage('key1');
    object1.innerHTML = key1;
    let key2 = await readLocalStorage('key1');
    object1.innerHTML = key2;

    continueCode();
}

or if you're not familiar with async/await behavior. You could wrap those 2 promises into an array and use Promise.all, like so:

function getData() {
    const key1 = readLocalStorage('key1');
    const key2 = readLocalStorage('key2');

    Promise.all([key1, key2]).then(values => {
        object1.innerHTML = values[0];
        object2.innerHTML = values[1];

        continueCode();
    });
}
like image 59
Toan Quoc Ho Avatar answered Feb 04 '26 15:02

Toan Quoc Ho


Here is a simplified answer to achieve this if you can change getData() to async:

async function getData() {
    var result = await chrome.storage.local.get('key');
    if (Object.values(result)[0] != undefined) {
        object1.innerHTML = Object.values(result)[0].val;
    }

    result = await chrome.storage.local.get('key2')
    if (Object.values(result)[0] != undefined) {
         object2.innerHTML = Object.values(result)[0].val;
    }

    continueCode();
}

The important part is you can simply await the result.

result = await chrome.storage.local.get(key);

Note: You can get both data from key1 and key2 in one call by passing them together in the array.

like image 32
Anurag Chatterjee Avatar answered Feb 04 '26 15:02

Anurag Chatterjee