等待从 storageArea 收集数据

Wait for data collection from storageArea

我在从存储中收集数据时遇到了一个问题。我在等待特定事件的后台脚本中有 onMessage 事件侦听器。如果收到此事件 - 我需要从 storageArea 收集一些数据,然后将其发送到内容脚本。我的问题是我需要等待这些数据被收集(成功与否)然后才继续发送数据。如果我尝试从 storageArea 回调发送它 - 我的内容脚本没有收到任何东西。如果我继续 -> 脚本继续并且不等待数据被收集并且我的内容脚本再次没有收到任何东西。下面是说明我的问题的伪代码:

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
     //get the data from the storageArea
 var storageData = {};
 browser.storage.local.get("myData", function (data) {
         //modify storageData here 
 });
  //send response ONLY when the data is finished loading(successfully or not)
  sendResponse(storageData);
});

所以我的问题是:我怎样才能等待数据被收集然后才继续?也许我不应该等待事件,我应该创建某种“事件链” 或回调?我还不确定如何组织这个。 非常感谢你们的帮助!

你可以做下面的例子吗

browser.storage.local.get(function(storageData){
    // modify storage data 
    // ... 

    sendResponse(storageData);
});

browser.storage.local.get() return 一个 Promisechrome.storage.local.get() return 一个回调函数。

您可以选择您喜欢的方式。

那就答应吧()

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
     
  //get the data from the storageArea
  browser.storage.local.get('myData')
  .then (storageData => {
    // do wathever with storageData
    sendResponse(storageData);
  })
  .catch(error => console.log(error)); // in case of error
});

async/await

browser.runtime.onMessage.addListener(async (request, sender, sendResponse) => {

  //get the data from the storageArea
  const storageData = await browser.storage.local.get('myData');
  // do wathever with storageData
  sendResponse(storageData);
});

回调函数

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
     
  //get the data from the storageArea
  chrome.storage.local.get('myData', storageData => {
    // do wathever with storageData
    sendResponse(storageData);
  });
});