我正在使用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,
如果有办法异步执行此操作。
如果有人可以回复相关文档或示例的链接,我真的很感激!
答案 0 :(得分:0)
h.open('HEAD', url, false);
第三个参数(false
)定义请求是异步还是同步....应该设置为true:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp database_number
是否大于0。答案 1 :(得分:0)
有一些令人敬畏的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
});