【发布时间】:2022-03-26 02:59:37
【问题描述】:
我一直看到 Promise 与 setTimeout 一起工作,但我试图根据 chrome.runtime.sendMessage 返回到 Promise 的任何内容来实现它。
我有一个内容脚本,一旦脚本完成,它就会执行此功能。
chrome.runtime.sendMessage({complete: true});
我有一个后台脚本,它循环遍历数组中的每个项目,并使用其中一个值打开带有 chrome.tabs.update 的 URL。
我想做的是让异步函数等待内容脚本发送的消息,并且只有在收到消息后才继续下一次迭代,尽管我不知道如何实现这一点,因为我'只见过 setTimeout 的例子。
应该是这样的
- 打开数组中的第一项并停止
- 在该页面上执行内容脚本并在最后执行 sendMessage。
- 现在后台脚本应该等待 sendMessage 被接收,然后再转到下一个项目。
- 一旦使用 onMessage 接收到 sendMessage,它应该转到下一个和项目并从第 2 步开始重复
这是后台脚本。
chrome.storage.local.get('userItems', function(result) {
console.log(result.userItems);
function delay() {
// I suppose I should do something with onMessage in the delay function
return new Promise(resolve => setTimeout(resolve, 500));
}
async function delayedLog(item) {
await delay();
console.log(item);
var url = "http://www.example.com/" + item.Category;
chrome.tabs.update({
url: url
});
}
async function processArray(array) {
for (const item of array) {
await delayedLog(item);
}
}
processArray(result.userItems);
});
【问题讨论】:
-
你可以简单地加载 Mozilla 的 WebExtensions polyfill 并使用 browser.runtime.sendMessage 等等,它会产生一个 Promise 以便你可以等待它。
标签: javascript google-chrome google-chrome-extension async-await