title: What is the best design pattern for asynchronous message passing in a Chrome extension?
body: <p>I have a background script that is responsible for getting and setting data to a localStorage database. My content scripts must communicate with the background script to send and receive data.</p>
  
  <p>Right now I send a JSON object to a function that contains the command and the data. So if I'm trying to add an object to the database Ill create JSON that has a command attribute that is addObject and another object that is the data. Once this is completed the background scripts sends a response back stating that it was successful.</p>
  
  <p>Another use case of the function would be to ask for data in which case it would send an object back rather than a success/fail.</p>
  
  <p>The code gets kind of hacky once I start trying to retrieve the returned object from the background script.</p>
  
  <p>It seems like there is probably a simple design problem to follow here that I'm not familiar with. Some people have suggested future/promise design problems but I haven't found a very good example.</p>
  
  <p>Content Script</p>
  
  <pre><code>function sendCommand(cmdJson){
     chrome.extension.sendRequest(cmdJson, function(response){
         //figure out what to do with response
     });
  }
  </code></pre>
  
  <p>Background script</p>
  
  <pre><code>if (request.command == "addObject"){
    db[request.id]= JSON.stringify(request.data); 
     sendResponse("success");
  }
  else if(request.command == "getKeystroke"){
   var keystroke = db[request.id];
   sendResponse(keystroke);
  }
  </code></pre>