Created by Kostas Minaidis | Dec 2018
async function connect(){ ... }
An async(hronous) function operates asynchronously, using an implicit Promise to return its result.
The syntax and structure is much more like using standard synchronous functions.
Open your console and compare the result of the following commands:
function normal(){ return 42; }
async function normal(){ return 42; }
async function connect(){
const result = await promiseCommand();
}
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.
Remember, the await keyword is only valid inside async functions.
CodePenTime for a CodePen:
https://bit.ly/2Rl0PU6function run( arg1, arg2 ){
if ( typeof arg1 === "undefined" ){
arg1 = "default value #1";
}
if ( typeof arg2 === "undefined" ){
arg2 = "default value #2";
}
console.log( arg1, arg2 );
}
run();
run( 1 );
run( 1, 2 );
function run( arg1 = "default #1", arg2 = "default #2" ){
console.log( arg1, arg2 );
}
run();
run( 1 );
run( 1, 2 );
Destructuring allows you to pull out data from arrays
and objects into distinct variables with concise syntax.
const address = {
street: 'Street',
city: 'Athens',
country: 'Greece'
}
const street = address.street;
const city = address.city;
const country = address.country;
const address = {
street: 'Street',
city: 'Athens',
country: 'Greece'
}
const { street, city, country } = address;
const address = {
street: 'Street',
city: 'Athens',
country: 'Greece'
}
const { street } = address;
const { city: town } = address;
function doStuff( one, two, options ) {
console.log( options.a, options.b, options.c );
}
doStuff( 'example1', 'example2', {
a: 'opt1',
b: 'opt2',
c: 'opt3'
});
function doStuff( one, two, { a, b, c } ) {
console.log( a, b, c );
}
doStuff( 'example1', 'example2', {
a: 'opt1',
b: 'opt2',
c: 'opt3'
});
function doStuff( one, two, { a = 'opt1', b = 'opt2', c = 'opt3' } = {} ) {
console.log( a, b, c );
}
doStuff( 'example1', 'example2' );
let colors = [ 255, 100, 55 ];
let [ red, green, blue ] = colors;
With default values:
let colors = [ 255, 100 ];
let [ red = 99, green = 99, blue = 99 ] = colors;
let colorA = "Black";
let colorB = "White";
[ colorA, colorB ] = [ colorB, colorA ];
colorA; // "White"
colorB; // "Black"
const first = [ 1, 2, 3 ];
const second = [ 4, 5, 6 ];
const combined = first.concat( second );
// [ 1, 2, 3, 4, 5, 6 ]
const combined = [ ...first, ...second ];
// [ 1, 2, 3, 4, 5, 6 ]
const combined = [ ...first, 'middle', ...second, 'end' ];
// [ 1, 2, 3, 'middle', 4, 5, 6, 'end' ]
const clone = [ ...first ];
const first = { name: "Kostas" };
const second = { job: "Instructor" };
const combined = { ...first, ...second, location: "Greece" };
console.log( combined );
// { name: "Kostas", job: "Instructor", location: "Greece" }
const clone = { ...first };