您可能误解了异步调用的含义(和内部工作原理)。
我会提出以下方法:
提供要执行的 URL 列表和回调,其中未访问的 URL 列表作为参数(在所有 URL 的历史记录检查完成后)。
对于原始列表中的每个 URL
:检查它是否已被访问(如果是,则将其添加到未访问的 URL 列表中)。
湾。增加一个checkedURLs
计数器。
C。检查是否所有 URL 都已(异步)检查,即checkedURLs
等于原始 URL 列表的长度。
当您检测到所有 URL 都已被检查(参见2.c.)时,执行指定的回调(参见1.),将未访问的 URL 列表作为参数传递。
演示扩展的一些示例代码:
清单.json:
{
"manifest_version": 2,
"name": "Demo",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": { "default_title": "Demo Extension" },
"permissions": ["history"]
}
背景.js:
/* List of URLs to check against */
var urlList = [
"http://stackoverflow.com/",
"http://qwertyuiop.asd/fghjkl",
"https://www.google.com/",
"https://www.qwertyuiop.asd/fghjkl"
];
/* Callback to be executed after all URLs have been checked */
var onCheckCompleted = function(unvisitedURLs) {
console.log("The following URLs have not been visited yet:");
unvisitedURLs.forEach(function(url) {
console.log(" " + url);
});
alert("History check complete !\n"
+ "Check console log for details.");
}
/* Check all URLs in <urls> and call <callback> when done */
var findUnvisited = function(urls, callback) {
var unvisitedURLs = [];
var checkedURLs = 0;
/* Check each URL... */
urls.forEach(function(url) {
chrome.history.getVisits({ "url": url }, function(visitItems) {
/* If it has not been visited, add it to <unvisitedURLs> */
if (!visitItems || (visitItems.length == 0)) {
unvisitedURLs.push(url);
}
/* Increment the counter of checked URLs */
checkedURLs++;
/* If this was the last URL to be checked,
execute <callback>, passing <unvisitedURLs> */
if (checkedURLs == urls.length) {
callback(unvisitedURLs);
}
});
});
}
/* Bind <findUnvisited> to the browser-action */
chrome.browserAction.onClicked.addListener(function() {
findUnvisited(urlList, onCheckCompleted);
});