title: Using promises with chrome.runtime messaging system
body: <p>In my chrome extension project, I'm using ES6 promises to get the result of XHR from the background page and send it to the content but I'm getting <code>undefined</code> as the value of <code>response</code> in the content. The XHR works fine, it returns a value.</p>
  
  <p>BTW, queue.js is just my small sugar for ES6 promises.</p>
  
  <p>queue.js</p>
  
  <pre><code>function defer() {
      let resolve = null;
      let reject = null;
      let promise = new Promise((_resolve, _reject) =&gt; {
          resolve = _resolve;
          reject = _reject;
      });
  
      return {
          'promise': promise,
          'resolve': resolve,
          'reject': reject
      };
  }
  
  module.exports = defer;
  </code></pre>
  
  <p>Content:</p>
  
  <pre><code>let Q = require('./queue');
  let cb = Q();
  
  function callback(response) {
      if (response) {
          let {result, data} = response;
  
          if (result === 'OK') {
              cb.resolve(data);
  
          } else if (result === 'KO') {
              cb.reject(data);
          }
      }
  }
  
  chrome.runtime.sendMessage({
      'event':'some_event',
      'data': {
          'user': 'test',
          'password': '1234'
      }
  }, callback);
  
  return cb.promise;
  </code></pre>
  
  <p>Background:</p>
  
  <pre><code>chrome.runtime.onMessage.addListener((message, sender, sendResponse) =&gt; {
      $.ajax({
          'url': 'I intentionally removed the URL to protect the innocent.',
          'method': 'POST',
          'dataType': 'json',
          'contentType': 'application/json; charset=UTF-8',
          'data': JSON.stringify({
              'username': message.data.user,
              'password': message.data.password
          })
      }).then((xhr) =&gt; {
          sendResponse({
              'result': 'OK',
              'data': xhr.token
          });
      }).fail((xhr) =&gt; {
          sendResponse({
              'result': 'KO',
              'data': null
          });
      });
  });
  </code></pre>