我正在使用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
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句