Как избежать ошибки "Порт сообщения закрыт до получения ответа" при использовании await в слушателе

Я пишу расширение Chrome с модулем узла "Chrome-extension-async" и сталкиваюсь с проблемой при использовании await в слушателе фона.

Файл content.js, который будет вставлен в страницу, отправит сообщение в фоновый режим с просьбой выполнить некоторые операции ввода-вывода, которые являются асинхронными:

// content.js
const package = await chrome.runtime.sendMessage({param: ...})
console.log(package)

// background.js
chrome.runtime.onMessage.addListener(async (request, sender, 
sendResponse) => {
    const value  = await doIOOperation();
    sendResponse(value);
})

Тем не менее, Chrome сообщит об ошибках, как показано ниже:

Uncaught (в обещании) Ошибка: порт сообщения закрыт до получения ответа.

Я думаю, что должен быть некоторый конфликт при использовании async / await в слушателе. Кто-нибудь знает, как решить эту проблему?

2 ответа

      const asyncFunctionWithAwait = async (request, sender, sendResponse) => {...}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    asyncFunctionWithAwait(request, sender, sendResponse)

    return true
})

работал на меня

Чтобы расширить все заметки и уточнить ответ @RomanistHere:

      // a couple example async example functions
var greet;
const whatever = async function(){
    greet = "hello";
}
const getSomething = async function(){
    return "bob";
}

// set up a function outside the callback, 
// ... giving freedom to leverage async/await.
const asyncFunctionWithAwait = async (request, sender, sendResponse) => {
    
    // now we can do await's normally here
    await whatever();
    let name = await getSomething();
    
    // since our response function is carried through "by reference",
    // therefore we can call it as if it were within the listener callback.
    sendResponse(greet + name)

}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    // exec in the body of this callback,
    // ... passing original function through.
    asyncFunctionWithAwait(request, sender, sendResponse)

    // per:
    // http://developer.chrome.com/extensions/runtime.html#event-onMessage
    //
    // This function becomes invalid when the event listener returns, 
    // unless you return true from the event listener to indicate you 
    // wish to send a response asynchronously (this will keep the message 
    // channel open to the other end until sendResponse (3rd arg) is called).
    return true;

});
Другие вопросы по тегам