JSFiddle - React, Tailwind, and code Playground
by kontrach
JavaScript
/* [start] Destructuring tricks */
const {
querySelector: find,
querySelectorAll: findAll
} = document;
const elements = {
// Just for demo purpose. It won't work. Needs to be called as findAll.call(document, 'a')
links: findAll('a')
};
const {
links,
// add default values for cases when object in empty
links: {length: hasLinks = 0} = []
} = elements;
if (hasLinks) {
// could be [...links], but in case of typescript you would have an error, that
// [ts] Type 'NodeListOf<HTMLAnchorElement>' is not an array type.
// So, it's better to get used to write in this way
const requests = Array.from(links).map( ({href}) => window.fetch(href) );
Promise.all(requests)
.then(results => console.log(results));
}
/* [end] Destructuring tricks */
// The same in ES5
var find = document.querySelector;
var findAll = document.querySelectorAll;
var elements = {
links: findAll('a')
};
var links = elements.links || [];
var hasLinks = links.length || 0;
if (hasLinks) {
var requests = Array.prototype.slice.call(links)
.map( function(link) {
return window.fetch(link.href)
});
// No analog for promises in ES5. External libs are requared.
// Promise.all(requests)
// .then(results => console.log(results));
}