【问题标题】:Combining multiple callbacks in javascript在javascript中组合多个回调
【发布时间】:2020-09-21 13:59:08
【问题描述】:

在我的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】:

    你应该在 A1 函数中返回 promise,像这样:

    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
    });
    

    【讨论】:

    • chrome.runtime.onMessage.addListener 响应中接收null
    • 那可能是因为 processMsg 是空的,现在试试
    • 我正在从 processMsg 返回内容。它仍然给出 null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多