-1

I'm developing a Chrome extension using VueJS. I store some data using chrome.storage.sync and I want to retrieve it later than iterate through it.

This is the code of the method that I use to get the data.

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

The console.log(value.speedDials) outputs the expected result, an array that contains several objects. But the return is an empty array. How can I debug this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Oussama He
  • 555
  • 1
  • 10
  • 31
  • I don't know this Chrome API, but I'm guessing it's async. If you log speedDials right before it's returned, I'd guess you see that being logged before the log inside the `get` – Thor Jacobsen Apr 12 '19 at 08:42
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Apr 12 '19 at 08:42

2 Answers2

0

return a promise from getSpeedDials function.

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. 
  }); 
 })
}
Swarup Bam
  • 166
  • 1
  • 9
0

chrome.storage.sync.get is async. You're returning the initial empty array before the values are loaded from the storage.

You can return a promise that resolves with the result when it's done.

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

Note that when you do this, getting the value should also be done differently.

Inside of an async function, we can use await to get the value:

let speedDials = await getSpeedDials();

If not:

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)

Let me know if you have any questions

Tim VN
  • 1,183
  • 1
  • 7
  • 19