0

I'm building a Chrome Extension and want to get some data from local storage.

function Extension() {
  function getUser(callback) {
    chrome.storage.sync.get('user', function(user){
      callback(user);
    });
  }
  this.getUser = getUser;
});

var extension = new Extension;

Allows me to do the following elsewhere:

extension.getUser(function(user){
  console.log(user);
});

=> The user object I'm hoping for! Hooray!

But I'd rather be able to just do something like:

var userData = extension.getUser();

And receive the user object in return.

I tried changing this.getUser = getUser to

this.getUser = getUser(function(user){
  return user;
});

But that didn't work.

console.log(extension.getUser);
=> undefined

I don't believe this to be a duplicate of this answer as I'm addressing the suggestion to pass a callback function to the async request. (How do I return the response from an asynchronous call?)

To expand even further, if I modify my code to read

 this.getUser = getUser(function(user){
     console.log(user);
 });

It does log the user object to the console! So close! I seem to be successfully retrieving the object by passing a callback to the function. But my question is how can I do that in a succinct way elsewhere in my code?

===== EDIT =====

If I save a userData object as a property of the Extension function like so:

var that = this;

this.getUser = getUser(function(user){
    that.userData = user;
});

Then I can make the following clean call elsewhere in my code and it's working.

var user = extension.userData;

Is there a drawback to this or is there a cleaner way to assign userData to the Extension without the this/that method?

Community
  • 1
  • 1
brianrhea
  • 3,674
  • 3
  • 34
  • 57
  • Note: Using [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) has very significant restrictions on compatible [browser versions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Browser_compatibility). You would be better off learning how to write code that is intended to be used with the asynchronous nature of most of the Chrome extension APIs, as the knowledge of how to do so will be beneficial in other programming projects, rather than limiting yourself to only pseudo-synchronous programming. – Makyen Dec 07 '16 at 22:08
  • Thanks @Mayken, I'm not going to use await in this case. – brianrhea Dec 07 '16 at 22:17
  • In my opinion, you can use async/await, since it can be polyfilled with generators/yield and chrome api promises can also be pollyfilled: github.com/mozilla/webextension-polyfill – Daniel Herr Dec 08 '16 at 00:20

0 Answers0