ECMAScript new features in 2017


Some of new ECMAScript features can boost your productivity a lot.

I would like to introduce some of my favorite features!

๐Ÿฃ Fetch JSON with async/await

Fetch JSON by URL is as follows:

async function fetchAsync() {
const response = await fetch("https://api.github.com");
return await response.json();
return data;
}

fetchAsync()
.then(data => console.log(data))
.catch(error => console.log(error.message));

The above code runs in the above environment:

๐ŸŽ‰ Spread syntax

Spread syntax allows an iterable such as an array expression or string to be expanded.

Some examples for array are as follows:

// Arguments to function
function myFunction(x, y, z) { /** do something */ }
const args = [0, 1, 2];
myFunction(...args);

// Apply new
const dateFields = [1970, 0, 1]; // 1 Jan 1970
const d = new Date(...dateFields);

// Powerful Array literal
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
// -> ["head", "shoulders", "knees", "and", "toes"]

// Copy Array
const arr = [1, 2, 3];
const arr2 = [...arr]; // -> [1, 2, 3, 4]

// Concatenate arrays
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
[...arr1, ...arr2]; // -> [0, 1, 2, 3, 4, 5, 6]

In addition, some examples of object literals:

const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };

// Clone Object
const obj3 = { ...obj1 }; // -> { foo: 'bar', x: 42 }

// Merge objects
const obj4 = { ...obj1, ...obj2 };
// -> { foo: 'baz', x: 42, y: 13 }

๐ŸŽƒ DataStruct Assignment

The DataStruct Assignment syntax makes it possible to unpack values from arrays or properties from objects.

// Object literals
const ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // -> 10
console.log(b); // -> 20
console.log(rest); // -> {c: 30, d: 40}

// Array
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // -> 10
console.log(b); // -> 20
console.log(rest); // -> [30, 40, 50]

๐Ÿ„ Async / Await

  • When an async function is called, it returns a Promise
  • When the async function returns a value, the Promise will be resoleved with the returned value
  • WHen the async function throws an exception or some value, the Promise will be rejected with the throw value

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promiseโ€˜s resolution, and then resumes the async functionโ€™s exection and returns the resolved value.

A simple example for await/async are as follows:

function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}

async function add1(x) {
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
}

add1(10).then(v => {
console.log(v); // prints 60 after 4 seconds.
});

When you use async/await, You can handle error by try-catch, like this:

function shouldBeFail(){
return Promise.reject(new Error('fail'));
}

(async function(){
try {
await shouldBeFail();
} catch(e) {
console.error(e); // fail
}

await shouldBeFail();
})().catch(e => console.error(e)); // 'fail'

๐Ÿ˜ผ Special Thanks

๐Ÿ–ฅ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!