H
H
hadaev_ivan2014-05-23 12:01:02
JavaScript
hadaev_ivan, 2014-05-23 12:01:02

Google Chrome Extension, chrome.storage.local: how to deal with asynchrony?

Using chrome.storage.local, I need to store an array accessible by the "block" key, and be able to add elements to it. But simply taking an array (.get(...)) and immediately inserting the modified (.set(...)) into it does not work. Interferes with asynchrony I so understand. How to bypass it?
Created the following structure:

var storage = chrome.storage.local,
      pb = {};  
pb.addBlock = function (value) {
    storage.get('block', function (item) {
      item = item || [];
      item.push(value);
      // ??? ваши предложения?)
      storage.set({block: item});
      // ??? ваши предложения?)
      return true;
    });
    return true;
  };

pb.addBlock('blabla');
//выкинет ошибку  Error in response to storage.get: TypeError: undefined is not a function

And I guess why it doesn’t work, I need to somehow wait for an answer, I can’t figure it out. Thank you for your attention :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hadaev_ivan, 2014-05-23
@hadaev_ivan

I'm sorry, I returned to the problem and immediately found what my problem was), asynchrony has nothing to do with it))
Working code:

var storage = chrome.storage.local,
      pb = {}; 
pb.addBlock = function (value) {
    storage.get('block', function (item) {
      item = item.block || [];
//  тут я и попался переменная item ссылается на объект 'block' в котором будет массив, а не сам массив
      item.push(value);
//  .push() на объект как раз и выкинет в следствии ту ошибку
      storage.set({block: item});
    });
    };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question