title: How to wait for the background script to finish before returning to the popup script?
body: <p>I have created a Chrome addon, for which when I click its toolbar button it brings up a popup message with some values in it. The popup script triggers a function in the background script which returns those values, while at the same time that function starts another callback function. The addon works fine, my problem is that I need to return the values from the background script back to the popup script, after the callback function has completed, not while it is running.</p>
  
  <p>here is the code</p>
  
  <p><strong>popup.js</strong></p>
  
  <pre><code>    document.addEventListener("DOMContentLoaded", function () {
          backGround = chrome.extension.getBackgroundPage();
          var msg = backGround.browserOnClickAxn();      
          insertText (msg);
          }
      );
  
      function insertText (msg) {
      do stuff
      }
  </code></pre>
  
  <p><strong>background.js</strong></p>
  
  <pre><code>    function browserOnClickAxn()
      {
  
      chrome_api_function (
      do stuff
      callback()
      )
  
      var result = another_function()
      var msg = result
      return msg; 
  
      }
  </code></pre>
  
  <p>What happens with the current code, is that the popup msg gets its values and appears while the callback() is still running. The callback() does its own thing, it has nothing to do with the generation of the msg values.</p>
  
  <p>I want the popup msg to get its values and appear only after the callback finishes.</p>
  
  <p>How do I approach this? I put a conditioned <em>while</em> before <em>var result</em>, to make the main function wait until the callback() returns a condition which stops the while, but the entire script halts.</p>
  
  <p>Do I use more callbacks? Do I use the SendMessage api of Chrome? I would like to solve this without over-complicating the existing code.</p>