我正在使用 JQuery 2.2.0 编写我的第一个 JavaScript Chrome 扩展,它基本上获取当前 URL 并轮询一些不同的 Web 服务以查看它们是否有 URL 记录。如果存在,我会在 DOM 中添加一个文本链接。这是一个简化的工作版本:
// Does the provided URL exist?
function url_exists(url) {
var h = new XMLHttpRequest();
h.open('HEAD', url, false);
h.send();
return h.status!=404;
}
// Display a link to the database record URL in the DOM
function display_database_link(url) {
$('body').prepend('<a href="' + url + '">Link</a>');
}
// Get the current URL
var url = window.location.href;
var database_number = 0;
// See if this URL exists in one of our databases via the API
// Does the URL exist in database 1?
if (url_exists("https://api.database1.com/urls/" + url)) {
database_number = 1;
}
// Does the URL exist in database 2?
else if (url_exists("https://api.database2.com/urls/" + url)) {
database_number = 2;
}
if (database_number > 0) {
display_database_link("https://api.database" + database_number + ".com/urls/" + url))
}
我所拥有的有效,但我想知道是否:
有一种方法可以同时多次调用 url_exists,并且
是否有办法异步执行此操作。
如果有人可以回复相关文档或示例的链接,我将非常感激!
最佳答案
有几个很棒的 es2015 功能可以让这一切变得美好而简单:fetch和 promises 。您必须进行一些调整,但类似这样的操作应该可行。
// Array of API endpoints to to make requests to
let url = window.location.href;
let database_urls = ["https://api.database1.com/urls/", "https://api.database2.com/urls/"];
// Promise.all will take an array of promises and perform all of them, and `then` process all results at the end
Promise.all(database_urls.map(database_url =>
// Make an HTTP request to the endpoint, and `then` get the status code from the response
fetch(database_url + url).then(response => response.status)
// Once `all` promises are resolved, `then` iterate over the resulting statuses
)).then(statuses => {
// Reduce `statuses` to a count of how many are not 404s
let existCount = statuses.reduce((prev, curr) => {return curr == 404 ? prev : prev + 1}, 0);
// Call method to display link if existsCount is > 0
});
关于javascript - 来自 Chrome 扩展程序的多个 Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542289/