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?