ECMAScript 2017

Main features

ES8

What's new?

How to use it?

Some examples

More about async functions

 What's new?

  • Object.values and Object.entries
  • Object.getOwnPropertyDescriptors
  • String padding
  • Trailing commas in functions
  • Shared memory and Atomics
  • Async functions

Object.values

Object.entries

The Object.values() method returns an array of a given object’s own enumerable property value.

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs.


  const obj = { foo: 'bar', baz: 42 };
  console.log(Object.entries(obj));

   [ ['foo', 'bar'], ['baz', 42] ]

Object.entres()


  const obj = { foo: 'bar', baz: 42 };
  console.log(Object.values(obj));

   ['bar', 42]

Object.values()

console

console

Object.getOwnProperty

Descriptors

The Object.getOwnPropertyDescriptors() method returns all of the own properties descriptors of the specified object.

  
  const obj = { 
    get es7() { return 777; },
    get es8() { return 888; }
  };
  console.log(Object.getOwnPropertyDescriptors(obj));
 
 {
   es7: {
     configurable: true,
     enumerable: true,
     get: function es7(){}, //the getter function
     set: undefined
   },
   es8: {
     configurable: true,
     enumerable: true,
     get: function es8(){}, //the getter function
     set: undefined
   }
 }

console

String padding

This section adds two functions to the String object: padStart & padEnd. This methods pad the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) or from the start (left) of the current string.

'es8'.padStart(2);          // 'es8'
'es8'.padStart(5);          // '  es8'
'es8'.padStart(6, 'woof');  // 'wooes8'
'es8'.padStart(14, 'wow');  // 'wowwowwowwoes8'
'es8'.padStart(7, '0');     // '0000es8'
'es8'.padEnd(2);          // 'es8'
'es8'.padEnd(5);          // 'es8  '
'es8'.padEnd(6, 'woof');  // 'es8woo'
'es8'.padEnd(14, 'wow');  // 'es8wowwowwowwo'
'es8'.padEnd(7, '6');     // 'es86666'

String.padStart()

String.padEnd()

Trailing commas in function parameter lists

Trailing commas in function parameter is the ability of the compiler not to raise an error (SyntaxError) when we add an unnecessary comma in the end of the list.

  
  function es8(var1, var2, var3,) {
    // ...
  }

  es8(10, 20, 30,);

  [10, 20, 30,]
  
  { x: 1, }

Shared Memory

and Atomics

Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted.

Async

functions

Help Dora find

multi-threading in JS

for(var i=0; i<3; i++){
	setTimeout(function(){
		console.log(i);
	}, 0);
}
3
3
3
0
1
2

     The async functions work much like generators, but they are not translated to generator functions  

 

    The async function declaration defines an asynchronous function, which returns an AsyncFunction object (creates a new async function). When an async function is called, it returns a Promise.

 

    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 execution and returns the resolved value.

 

GeneratorFunction

With generators, we have a different kind of function, which may be paused in the middle, one or many times, and resumed later, allowing other code to run during these paused periods. Inside the generator function body, you use the new yield keyword to pause the function from inside itself.

 
  function* fun() { ... }

syntax

function* idMaker() {
    var index = 0;
    while(true)
        yield index++;
}

var gen = idMaker(); // "Generator { }"

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

#1

function* gen() {
  let result = yield "2 + 2?";
  console.log(result);
}

let generator = gen();

let question = generator.next().value; 
// question == "2 + 2?" -> true

setTimeout(() => generator.next(4), 2000);
// console -> 4

#2

Promise

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

 
  new Promise( /* executor */ function(resolve, reject) { ... } );

syntax

var p1 = new Promise( (resolve, reject) => {
  resolve('Success!');
  reject ("Error!");
} );

p1.then( value => {
  console.log(value); // Success!
}, reason => {
  console.log(reason); // Error!
} );
var p1 = new Promise( (resolve, reject) => {
  resolve('Success!');
  reject ("Error!");
} );

p1.then( value => {
  console.log(value); // Success!
} ). catch(reason => {
  console.log(reason); // Error!
} );
p.then(function(value) {
  // fulfillment
}, function(reason) {
  // rejection
});
p.catch(function(reason) {
   // rejection
});

syntax

syntax

Await

The await operator is used to wait for a Promise. It can only be used inside an async function.

 
  [rv] = await expression;

syntax

expression - A Promise or any value to wait for.

rv - Returns the fulfilled value of the promise, or the value itself if it's not a Promise.

   (GENERATOR+PROMISE)+AWAIT=ASYNC

async function name([param[, param[, ... param]]]) {
   ...
}

syntax

async function unicorn() {
  let rainbow = await getRainbow();
  return rainbow.data.colors
}
function loadExternalContent() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('hello');
        }, 3000);
    });
}
async function getContent() {
    const text = await loadExternalContent();
    console.log(text);
}
console.log('it will call function');
getContent();
console.log('it called function');
'it will call function' // synchronous
'it called function'    // synchronous
'hello'                 // asynchronous (after 3 seconds)
  • When starts following the "await" code?
  • What if the function used with "await" does not return Promise?
  • What if I declare a function asynchronous, but do not use "await"?
async function unicorn() {
  let rainbow = getRainbow();
  return rainbow;
}
  • What happens if I write a few functions that use "await"?
async function unicorn() {
   let rainbow = await getRainbow();
   let food = await getFood();
   return {rainbow, food}
}

Q&A

Bye.

EcmaScript 2017

By Victoria Budyonnaya

EcmaScript 2017

  • 211