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

时间:2019-12-21 21:38:18

标签: asynchronous google-chrome-extension google-chrome-storage

我有两个打给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();
}

2 个答案:

答案 0 :(得分: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();
  }
}

答案 1 :(得分:0)

您可以利用Promiseasync/await来解决此问题。假设您要同步处理chrome.storage.local.get,以便continueCode()拥有所需的数据。

获取数据:

function readLocalStorage(key) {
    return Promise((resolve, reject) => {
        chrome.storage.local.get([key], function(result) {
            if (Object.values(result)[0] != undefined) {
                resolve(Object.values(result)[0].val);
            } else {
                reject();
            }
        });
    });
}

主要功能:


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

    continueCode();
}

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

function async getData() {
    let key1 = readLocalStorage('key1');
    let key2 = readLocalStorage('key2');

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

        continueCode();
    });
}

希望有帮助!