0

I'm building an extension that uses the chrome.storage.sync API. I know that I have to use async code for chrome.storage.sync.get because of reasons (i don't fully understand either) by using async/await. Should I make the function that calls chrome.storage.sync.set asynchronous too? Should all chrome extension API calls be async?

Little more info: I'm using react so maybe it has something to do with the component life cycle or the event loop? I have no idea I'm very new.

feverdreme
  • 467
  • 4
  • 12

1 Answers1

0

The short answer: there's no need to mark the Chrome storage callback async unless you want to use await. You also don't need to mark a function that calls the Chrome storage API as async.

Examples:

// works just fine without async
chrome.storage.sync.get('someKey', function(obj) {
   console.log(obj)
})

// async allows you to use await in the callback function with Promises
chrome.storage.sync.get('someKey', async function(obj) {
   var response = await fetch('...');
})

// no need to make the outer `setData` function async
function setData() {
  chrome.storage.sync.set({someKey: 123, function() {
    // ...
  })
}

Marking a function as async is basically just to use the await keyword within it. await is handy because it solves "callback hell", where you have many functions that require callbacks and you have to chain them together.

Additionally, one day (see this bug) Chrome's extensions API will return Promises instead of requiring callbacks as they do today, so writing Chrome extension code will use async functions a lot more. Firefox already uses Promises in their extension API, but for backward-compatibility reasons also supports using callbacks.

Glench
  • 155
  • 6
  • the thing is whenever I tried to call the function that calls chrome.storage.sync.get in my react component it always returned undefined, so I had to do the async await so I actually got a result – feverdreme Jan 03 '21 at 20:53
  • It would be super helpful to see a minimal example so we can see what's going on. But yeah, if that function you're calling is returning a Promise, then if you don't use either await or promise.then(callback) it probably won't work correctly. – Glench Jan 03 '21 at 22:10