我试图等待听众听完所有消息,然后再使用
console.log("Done")
继续 await
但它没有发生。我错过了什么。
const f = async (leftPaneRowEle,index) => {
leftPaneRowEle.scrollIntoView()
leftPaneRowEle.children[0].click()
console.log('downloadBtn clicked for', leftPaneRowEle)
const listener = (msg: any) => {
console.log('frontend msg:', msg)
}
const port = Browser.runtime.connect()
port.onMessage.addListener(async (msg, sender) => {
console.log("BG page received message", msg, "from", sender);
listener(msg)
});
await port.postMessage({ question: "Can you " + allTFBs[leftpaneindexes[index]] + ":" + desc })
return async () => {
await port.onMessage.removeListener(listener)
await port.disconnect()
}
}
const en: HTMLElement = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement
const leftPaneRowEle0 = en.children[leftpaneindexes[0]]
await f(leftPaneRowEle0,0)
console.log("Done")
PS:我的方法受到这个answer
的启发const f = (leftPaneRowEle, index) => {
return new Promise(async (resolve) => {
leftPaneRowEle.scrollIntoView();
leftPaneRowEle.children[0].click();
console.log('downloadBtn clicked for', leftPaneRowEle);
const listener = (msg) => {
console.log('frontend msg:', msg);
};
const port = Browser.runtime.connect();
port.onMessage.addListener((msg, sender) => {
console.log("BG page received message", msg, "from", sender);
listener(msg);
});
port.onDisconnect.addListener(() => {
console.log("Port disconnected");
resolve(); // Resolve the Promise when the port disconnects
});
await port.postMessage({ question: "Can you " + allTFBs[leftpaneindexes[index]] + ":" + desc });
});
};
const en = document.querySelectorAll('#extensionListTable tbody')[0] as HTMLElement;
const leftPaneRowEle0 = en.children[leftpaneindexes[0]];
(async () => {
await f(leftPaneRowEle0, 0);
console.log("Done");
})();
试试这个