本文介绍了带有异步等待的chrome.runtime.onMessage响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在onMessage侦听器中使用异步等待:

I want to use async await in an onMessage listener:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey();
    sendResponse(key);
});

但是,当我发送消息时却变得不确定.

However I get undefined when I send a message.

从chrome.runtime.onMessage.addListener文档中:

From the documentation for chrome.runtime.onMessage.addListener:

这在我使用回调时有效.

This works when I use a callback.

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    getKey(key => {
        sendResponse(key);
    });
    return true;
});

但是我想利用await语法.但是它似乎不起作用,并且仍然返回undefined:

However I would like to leverage the await syntax. But it does not seem to work and still returns undefined:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey();
    sendResponse(key);
    return true;
});

推荐答案

我通过提取到异步函数来进行变通.

I do work-around by extracting to an async function.

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  doSomethingWith(request).then(sendResponse);
  return true; // return true to indicate you want to send a response asynchronously
});

async function doSomethingWith(request) {
  var key = await getKey();
  // await .....
  return key;
}

async函数的返回值隐式包装在Promise.resolve中.请参见异步文档.

The return value of an async function is implicitly wrapped in Promise.resolve. See async doc.

请参见 onMessage .

这篇关于带有异步等待的chrome.runtime.onMessage响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 01:12