sendResponse not waiting for async function or Promise’s resolve [duplicate]

The callback of onMessage should return a literal true value (documentation) in order to keep the internal messaging channel open so that sendResponse can work asynchronously.

Problem

Your callback is declared with async keyword, so it returns a Promise, not a literal true value. Chrome extensions API doesn’t support Promise in the returned value of onMessage callback until https://crbug.com/1185241 is fixed so it’s just ignored, the port is immediately closed, and the caller receives undefined in response.

Solutions

Remove the async keyword from before (request, sender, sendResponse), then…

Solution 1
Call an async function that can be embedded as an IIFE:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === "get_thumbnails") {
    (async () => {
      const payload = await getThumbnails();
      console.log("thumbPayload after function:", payload)
      sendResponse({payload});
    })();
    return true; // keep the messaging channel open for sendResponse
  }
});

Solution 2
Declare a separate async function and call it from the onMessage listener:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.message === "get_thumbnails") {
    processMessage(msg).then(sendResponse);
    return true; // keep the messaging channel open for sendResponse
  }
});

async function processMessage(msg) {
  console.log('Processing message', msg);
  // .................
  return 'foo';
}

Leave a Comment