chrome extension - sendResponse not waiting for async function

后端 未结 1 1371
粉色の甜心
粉色の甜心 2020-11-29 13:10

I am having an issue of asynchronicity (I believe). sendResponse() in contentscript.js does not wait for getThumbnails() to return

相关标签:
1条回答
  • 2020-11-29 14:07

    The callback of onMessage should return true in order to keep the internal messaging channel open so that sendResponse can work asynchronously.

    The problem is, your callback is declared with async keyword which means it returns a Promise so it can't return a literal true value because Chrome extensions API doesn't support Promise and hence can't resolve it.

    Use a standard function callback and a nested async 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
      }
    });
    
    0 讨论(0)
提交回复
热议问题