Promise from browser.runtime.sendMessage() fulfilling prior to asynchronous call to sendResponse()
<p>I have made a Firefox WebExtension that interacts with an executable (using <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/connectNative" rel="nofollow noreferrer"><code>runtime.connectNative</code></a>).</p>

<p>Here is the manifest of the extension:</p>

<pre><code>// manifest.json file

{
  "name": "My Extension",
  "short_name": "myext",
  "version": "2.7",
  "manifest_version": 2,
  "background": {
    "scripts": ["background-script.js"],
    "persistent": true
    },
    "externally_connectable": {
      "ids": ["*"],
      "http://localhost/*"]
  },
   "content_scripts": [
    {
      "matches": ["&lt;all_urls&gt;"],
      "js": ["content-script.js"]
    }
  ],
  "applications": {
    "gecko": {
      "id": "myext@myext.mysite.com",
      "strict_min_version": "50.0.0"
    }
  },
  "icons": {
    "16": "icon-16.png",
    "32": "icon-32.png",
    "128": "icon-128.png"
  },
  "permissions": [
       "nativeMessaging",
       "webRequest"
    ]
}
</code></pre>

<p>Here is the content script:</p>

<pre><code>// content-script.js

window.addEventListener("message", function(event) {
  if (event.source == window &amp;&amp;
      event.data.direction &amp;&amp;
      event.data.direction == "from-page-script") {
    alert("Content script received message: \"" + JSON.stringify(event.data.message) + "\"");

    var sending = browser.runtime.sendMessage(event.data.message);

    sending.then(handleResponse, handleError);

  }
});

function handleResponse(message) 
{
  console.log("content-script : handleResponse : message = " + JSON.stringify(message));
  window.wrappedJSObject.foo.p = "OK : " + JSON.stringify(message);
}

function handleError(error) {
  console.log("Message from the background script : " + error.message);
  window.wrappedJSObject.foo.p = "error";
}
</code></pre>

<p>And here is my background script:</p>

<pre><code>// background-script.js

var port;

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) 
{
    port = browser.runtime.connectNative("ping_pong");
    var result = port.postMessage(request);

    port.onMessage.addListener(function(response)
    {
        console.log("Received: " + JSON.stringify(response));
        sendResponse(response);
    });
});
</code></pre>

<p>I have a problem regarding the following line in the background script:</p>

<pre><code>sendResponse(response);
</code></pre>

<p>The method <code>handleResponse()</code> of the content script is called before the <code>sendResponse()</code> of the background script.</p>

<p>So, when the executable takes a longer time to do an action, the result of the executable is not sent to the content script, and the content script receives an undefined result.</p>

<p>Is there another way to send the result of the executable from the background script to the content script? Or use the callback another way?</p>