【问题标题】:When call method it returns empty array调用方法时返回空数组
【发布时间】:2019-04-12 08:39:34
【问题描述】:

我正在使用 VueJS 开发一个 Chrome 扩展程序。我使用chrome.storage.sync 存储了一些数据,并且我想在遍历它之前检索它。

这是我用来获取数据的方法的代码。

getSpeedDials() {
  let speedDials = [] 
  chrome.storage.sync.get('speedDials', function(value)  { 
    if (value.hasOwnProperty('speedDials')) { 
      console.log(value.speedDials) 
      speedDials = value.speedDials 
    } 
  }); 
return speedDials 
}

console.log(value.speedDials) 输出预期的结果,一个包含多个对象的数组。但返回的是一个空数组。我该如何调试?

【问题讨论】:

标签: javascript vue.js google-chrome-extension


【解决方案1】:

从 getSpeedDials 函数返回一个承诺。

getSpeedDials() {
 return new Promise((resolve,reject) => {
   let speedDials = [] 
   chrome.storage.sync.get('speedDials', function(value)  { 
   if (value.hasOwnProperty('speedDials')) { 
     console.log(value.speedDials) 
     speedDials = value.speedDials;
     return resolve(speedDials);
   } 
   return resolve();
  // you can reject promise if you want to treat this as an error. 
  }); 
 })
}

【讨论】:

    【解决方案2】:

    chrome.storage.sync.get 是异步的。在从存储中加载值之前,您将返回初始空数组。

    您可以返回一个承诺,当它完成时,它会以结果解析。

    async getSpeedDials() {
        return new Promise(resolve => {
            chrome.storage.sync.get('speedDials', result => {
                resolve(result);
            });
        }
    }
    

    请注意,当您这样做时,获取值也应该以不同的方式进行。

    async函数内部,我们可以使用await来获取值:

    let speedDials = await getSpeedDials();
    

    如果没有:

    let speedDials = [];
    getSpeedDials().then(dials => {
        speedDials = dials
    });
    // Note that when doing this, everything under this function will be executed before speedDials has any entries.
    // To prevent this, make your function async, and use the aforementioned method (await)
    

    如果您有任何问题,请告诉我

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 2021-08-17
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多