Section 18: ES2016 and ES2017 Flashcards
Exponentiation Operator **
two to the power of four
var calculatedNumber = 2**4
calculateNumber; // 16
[].includes
var nums = [1,2,3,4,5]
nums. includes(3); // true
nums. includes(44); // false
padStart and padEnd
*allows us to designate exactly how long a string should be, and what to use to make it longer if it needs to be lengthened.
“awesome”.padstart(10); // “ awesome”
“awesome”.padstart(10, !); // “!!!awesome”
Async Functions and ‘await’ keyword
*Special kind of function that can be paused using the ‘await’ keyword. Await, waits for a promise to be resolved before continuing.
async function getMovieData(){
console.log(“starting!”);
var movieData = await $.getJSON(‘https://omdbapi.com?t=titanic&apikey=thewdb’);
// this line does NOT run until the promise is resolved
console.log(“all done!”);
console.log(movieData);
}
getMovieData() // logs an object with data about the movie!
How do you optimize performance while using async functions and ‘await’?
Make sure you’re doing them in parallel rather than sequentially.
async function getMovieData(){ var titanicPromise = $.getJSON(`https://omdbapi.com?t=titanic&apikey=thewdb`); var shrekPromise = $.getJSON(`https://omdbapi.com?t=shrek&apikey=thewdb`);
var titanicData = await titanicPromise; var shrekData = await shrekPromise;
console.log(titanicData);
console.log(shrekData);
}
getMovieData();
How do you handle errors while using async and await?
You use try/catch statements:
async function getUser(user) { try { var response = await $.getJSON(`https://api.github.com/users/${user}`); console.log(response.name); } catch(e){ console.log("User does not exist!"); } }
What is a great way to await multiple resolved promises?
** Use the Promise.all operator
async function getMovieData(first, second){
var moviesList = await Promise.all([
$.getJSON(https://omdbapi.com?t=${first}&apikey=thewdb
),
$.getJSON(https://omdbapi.com?t=${second}&apikey=thewdb
)
]);
console.log(moviesList[0].Year);
console.log(moviesList[1].Year);
}
getMovieData(‘shrek’, ‘blade’);