asynchronousgoogle-chrome-extensiongoogle-chrome-storage

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();
}

Solution

  • You need to wait for both callback function that you pass to chrome.storage.local.get(..) to be executed before you call continueCode(), also, you can check both storage properties with a single call, here is an example:

    function getData() {
      chrome.storage.local.get(['key', 'key2'], function(result) {
        if (typeof result.key !== 'undefined') {
          object1.innerHTML = result.key.val;
        } 
        if (typeof result.key2 !== 'undefined') {
          object2.innerHTML = result.key2.val;
        } 
        continueCode();
      }
    }