如何在继续执行之前等待异步 chrome.storage.local.get() 完成

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

我打了两次电话给 chrome.storage.local.get()。在继续为我的 chrome 扩展程序执行其余代码(调用 continueCode() 函数)之前,我需要完成这些调用,但我不确定如何执行此操作,这是我的代码。

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

你需要等待你传递给chrome.storage.local.get(..)的两个回调函数在你调用continueCode()之前执行,另外,你可以一次调用检查两个存储属性,这里是示例:

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

您可以使用new Promiseasync/await来处理这个问题。假设您要同步处理 chrome.storage.local.get,以便 continueCode() 可以获得所需的数据。

获取数据:

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

主要功能:


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

    continueCode();
}

或者如果您不熟悉 async/await 行为。您可以将这 2 个承诺包装到一个数组中并使用 Promise.all,如下所示:

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