Skip to content

Instantly share code, notes, and snippets.

@bbbbruni
Last active July 16, 2018 00:30
Show Gist options
  • Save bbbbruni/578352bb7acf9c493606b4a264807370 to your computer and use it in GitHub Desktop.
Save bbbbruni/578352bb7acf9c493606b4a264807370 to your computer and use it in GitHub Desktop.
ES7/8 features

Async / Await

  • Only works with promise protocol;
  • async is only called at the beggining of a function;
  • await can be used only with an async function;
  • await is used to tell the function to wait until resolve of a promise;

🚀 Advantages:

  • Better code readability;
  • Better debugging;
  • Less callbacks;
  • Less threaded code;

Using fetch

fetch('https://api.github.com/users/brunob182')
  .then(data => data.json())
  .then(data => console.log(data.html_url))
  // => "https://github.com/brunob182"

Using async/await

async function getUser() {
 // Wait until promise is resolved
 const response = await fetch('https://api.github.com/users/brunob182')
 
 // Wait the response of the promise
 const data = await response.json()
	
 console.log(data.location) // => Curitiba / Brazil
}

getUser();

Handling errors with try...catch

async function getUser() {
  try {
    const response = await fetch('https://api.github.com/users/ASDASDFASFASFGASFASDFASD');
    const data = await response.json();
    return data.location;
  }
  catch (err) {
    console.log(err);
  }
}
  
getUser();

Handling multiple async promises

async function getUser(user) {
  const promise = user.map(users => fetch(`https://api.github.com/users/${users}`).then(r => r.json()));
  const usersResp = await Promise.all(promise);
  usersResp.map(user => console.log( user.name ));
  // Bruno Almeida, Vinicius Brasil, Fábio Tomio
}

getUser(['brunob182', 'vnbrs', 'fabiotomio']);

String

  • String.prototype.padStart();
  • String.prototype.padEnd();

To know more on MDN

Exponentiation

Old way:

Math.pow(2, 6); // 64

New and better way:

(2 ** 6); // 64

Array

Array.includes()

[1, 2, 3, 4, 5, 6].includes(5); // true

Objects

Object.entries()

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

MDN Doc

Object.values()

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

MDN Doc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment