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

12

我有两个调用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();
}
3个回答

33
你可以使用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个promises包装到数组中并使用 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();
    });
}

我需要 new Promise,而不仅仅是 Promise - Rokit
2
function async getData() 给我报错了。将代码改为 async function getData() 后问题得到解决。 - Amit Sharma

0

https://developer.chrome.com/docs/extensions/reference/storage/#asynchronous-preload-from-storage提供了一个异步获取Chrome存储的示例。他们使用了以下函数。(我修改了它以便能够返回任何顶级键)

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

// It can be called like this:
var obj = await getAllStorageSyncData(['key','key2']);
// obj will have obj.key and obj.key2

null作为顶级键返回所有键。


-1

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

我在存储和获取两个不同键的对象方面遇到了一些问题,但我会尝试这个方法。 - nosh
因此,如果if条件被检查并且为真,则continueCode()将立即执行,并设置对象的innerHTML,因为在我的continueCode()中,我通过调用document.getElementById()从HTML中获取object1或object2。 - nosh
也许问题在于我使用的是 chrome.storage.local 而不是 chrome.storage.sync - nosh
@NoahTanenholtz,你的意图不太清楚。我认为使用 local 而不是 sync 不是问题所在,你可以从文档了解存储的工作原理,这只是基本的JavaScript,需要使用回调函数并检查对象的属性。 - Titus
由于我需要保密规格并且这是用于特定网站的Chrome扩展程序,所以有点难以解释我正在尝试做什么。但是,这段代码确实可以使用chrome.storage API同时获取两个键值对。 - nosh
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接