Skip to main content

2 posts tagged with "ES2018"

View All Tags

`Promise.prototype.finally`

· 2 min read
Mathias Bynens ([@mathias](https://twitter.com/mathias))

Promise.prototype.finally enables registering a callback to be invoked when a promise is settled (i.e. either fulfilled or rejected).

Imagine you want to fetch some data to show on the page. Oh, and you want to show a loading spinner when the request starts, and hide it when the request completes. When something goes wrong, you show an error message instead.

const fetchAndDisplay = ({ url, element }) => {
showLoadingSpinner();
fetch(url)
.then((response) => response.text())
.then((text) => {
element.textContent = text;
hideLoadingSpinner();
})
.catch((error) => {
element.textContent = error.message;
hideLoadingSpinner();
});
};

Object rest and spread properties

· 2 min read
Mathias Bynens ([@mathias](https://twitter.com/mathias))

Before discussing object rest and spread properties, let’s take a trip down memory lane and remind ourselves of a very similar feature.

ES2015 array rest and spread elements

Good ol’ ECMAScript 2015 introduced rest elements for array destructuring assignment and spread elements for array literals.

// Rest elements for array destructuring assignment:
const primes = [2, 3, 5, 7, 11];
const [first, second, ...rest] = primes;
console.log(first); // 2
console.log(second); // 3
console.log(rest); // [5, 7, 11]

// Spread elements for array literals:
const primesCopy = [first, second, ...rest];
console.log(primesCopy); // [2, 3, 5, 7, 11]

ES2018: object rest and spread properties 🆕

So what’s new, then? Well, a proposal enables rest and spread properties for object literals, too.

// Rest properties for object destructuring assignment:
const person = {
firstName: 'Sebastian',
lastName: 'Markbåge',
country: 'USA',
state: 'CA',
};
const { firstName, lastName, ...rest } = person;
console.log(firstName); // Sebastian
console.log(lastName); // Markbåge
console.log(rest); // { country: 'USA', state: 'CA' }