0

I'm trying to make a Chrome extension using chrome.storage.sync, using the following object:

var storage = {
  "area":chrome.storage.sync,

  "get":function(key){

    var result = true,
      callback = function(items){
        result = items[key];
      };

    this.area.get(key,callback);

    return result;
  },

  "set":function(key,value){
    //create an empty object for a key:value pair
    var object = {};

    object[key] = value;

    console.log(object);

    this.area.set(object,function(){
     console.log(object);
    });

  }
};

But the "get" method never returns the result. It only returns "true" in this example. Why can't I get the actual value of the item, store it in result, and return it? Does it take time for Chrome to fetch the key:value pairs? If so, how do I work around this?

RickyAYoder
  • 963
  • 1
  • 13
  • 29

1 Answers1

0

Since chrome.storage operations are asynchronous, you should pass your callback function when calling the get method instead.

var storage = {
  "area":chrome.storage.sync,

  "get":function(key, callback){    
    this.area.get(key,callback);
  },

  "set":function(key,value){
    //create an empty object for a key:value pair
    var object = {};

    object[key] = value;

    console.log(object);

    this.area.set(object,function(){
     console.log(object);
    });

  }
};

Call it with:

var callback = function(items) {
    // get your object from chrome.storage here
    // and perform your actions.
    console.log(items);
}
storage.get(key, callback);
jianweichuah
  • 1,417
  • 1
  • 11
  • 22