在javascript中组合多个回调

问题描述 投票:0回答:1

在我的回电中 chrome.runtime.onMessage.addListener 得到未定义或 True. 当 chrome.runtime.onMessage.addListener 接收到消息后,它会与本地应用程序进行通信,并检索一个响应。我想将该响应返回给 chrome.runtime.onMessage.addListener 响应。我试着学习梳理两个回调,但在那边没有任何运气。

async processMsg(response, param2) {}

async function A1(msg, sender) {
      await chrome.runtime.sendNativeMessage(hostName, mesg,async function(response) {
            var resp = await processMsg(response, param2);
            return resp;
        });

  return true;
}


chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
   A1(msg, sender).then(sendResponse);
    return true;
});
javascript async-await asynccallback
1个回答
0
投票

你应该在A1函数中返回承诺,像这样。

async processMsg(response, param2) {
    return "not null"
}

async function A1(msg, sender) {
    return await chrome.runtime.sendNativeMessage(hostName, mesg,async function(response) {
        return processMsg(response, param2);
    });
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    A1(msg, sender).then(sendResponse);
    return true; //I don't think you need to return anything here
});
© www.soinside.com 2019 - 2024. All rights reserved.