Async/Await (syntactic sugar on top of Promises)

ref – https://www.toptal.com/javascript/asynchronous-javascript-async-await-tutorial

Promises paved the way to one of the coolest improvements in JavaScript. ECMAScript 2017 brought in syntactic sugar on top of Promises in JavaScript in the form of async and await statements.

Async

Declaring a function as async will ensure that it always returns a Promise so you don’t have to worry about that anymore.

The word “async” before a function means one simple thing: a function always returns a promise.

1st example

2nd example

We can explicitly return a the static function for class Promise:

Similarly,

So, async ensures that the function returns a promise, wraps non-promises in it.

Await

The await operator is used to wait for a Promise.

It can only be used inside an async function.

The await expression causes async function execution to pause until a Promise is fulfilled, that is resolved or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

The syntax:

The keyword await makes JavaScript wait until that promise settles and returns its result.

If there was no await, JS’s single thread will execute the async function, and down the main execution steps turn by turn. So that then end of your program will be executed even when your function is not done.


output:

running addAsync
here—–
NaN
doubleAfter2Seconds: 4
doubleAfter2Seconds: 6

As you can see, when your function is finally done, the result will be stranded. With nothing to execute the returned result.

Using await, it makes the JS thread wait until the promise is returned from the async function. Then proceeds to process it.

if you were to wrap a Promise object around our code, the await will wait for the resolve/reject before moving on…


output:

running addAsync
doubleAter2Seconds: 4
doubleAter2Seconds: 6
here—–
10

In a more simple example:

Let’s emphasize: await literally makes JavaScript wait until the promise settles, and then go on with the result.
That doesn’t cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.
(JS only has 1 thread, which can skip around and execute different tasks, doing a little at a time)

It’s just a more elegant syntax of getting the promise result than promise.then, easier to read and write.

If you wish to await two or more promises in parallel, you must still use Promise.all.

Examples of using both

Asynchronous execution
Await is used inside of the async.

When we call a function with async, it

1) returns a Promise object
2) runs asynchronously

You can see this asynchronous activity going on because as the function f runs, the JS execution also continues
down and logs “grandma says:….come to dinner…!!….”.

resolve, then

Whenever we deal with async functions, we must return a Promise. Thus we create a Promise, and make it run a setTimeout
function which is asynchronous. The setTimeout executes code after 3 seconds.

However, in our code, the Promise does not get returned right away due to the “await” statement. Rather, we must wait for the Promise to finish before moving on.
Therefore, the log statements and return Promise MUST wait for the Promise to resolve FIRST.
After the Promise executes its method, it then runs the rest of the statements.

No Await

If we remove the await, the promise gets created, then since there is no “await”, we continue executiong
with the log statements, and then returns the promise object.
Then the Promise executes the setTimeout, and resolves after 3 seconds.
The resolve will hit the “then” block.

The execution will run in this order:

start of f()
create new Promise object
Wait for the Promise to resolve
here….
there….
everywhere…!!….
return the Promise object
waited 3 sec
1ST THEN:oh yea!

Another Example

Another example shows that await actually stops execution on the await line within that async function. While it waits, the JS execution will still move on
to execute after the async functionK

This is shown at 10, where the new Promise object has been created and will be returned. When it returns the Promise object, execution will need wait for the Promise to finish. Since the Promise takes 2 seconds, JS execution will continue after the async func onto line 11.

After the 2 seconds, we resolve the Promise at line 12. Then go on to 13, which we now have the passed in parameter value from the Promise’s resolve.

Whenever you “await” for a Promise, the rest of the async function will not run. Because it is “awaiting” your Promise to finish.
However, it will continue to execute the code that takes place AFTER the async function.

Take note at var x, it is awaiting a Promise to resolve inside of resolveAfter2Seconds…while it is waiting, execution continues at 11.

One more…!

Encapsulation in JS

ref – https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/

Creating React Components

https://www.kirupa.com/react/components.htm

Concept

This is terrible coding because you are doing a lot of repetitive coding.

thus, functions were created:

…and therefore, we can easily call the functions and provide parameters:

How it Works in React

Now, in React, say we want to render a bunch of h1. We have a index.html template with a given div for us to inject html content into like so:

Then, in index.js we use React’s API to render some custom html:

this repetitive usage of the h1s is the equivalent of writing the same code over and over again. Because what if we want to change them to h3. Or add bold to it. Its tiring to change it for everyone one of them. Conceptually, we want to do something similar to as how functions have solved repetitive code.

React Components

React components are reusable chunks of JavaScript that output (via JSX) HTML elements

This is where we use JSX to generate and render html to throw into a specific div. In our case, it would be the id=root div.

You create a class that extends the features of component. We do so like this:

This HelloWorld component is a component because it extends React.Component. If it didn’t do that, it would just be an empty class that doesn’t do much.

Inside our class, you can put all sorts of methods to further define what HelloWorld does.
However, there is mandatory function called Render which you must implement.

What we’ve done so far might seem crazy, but simply think of your component as a cool and new HTML tag whose functionality you fully have control over. This means you can do all sorts of HTML-ey things to it.

Properties

Our Hello component isn’t very useful because it only says Hello to one thing. It cannot say hello to other people/things. Say we want to have the Hello be applied to different names.

Just like with functions, you can pass in arguments that alter what your component does. There is a slight terminology update you need to be on top of. What we call arguments in the function world are going to be known as properties in the component world. Let’s see these properties in action!

Right now, our HelloWorld component is hard-coded to always send out Hello, world! as part of its return value. The first thing we are going to do is change that behavior by having return print out the value passed in by a property.

We are going to modify our HelloWorld component to allow you to specify who or what you greet besides the generic World.

Adding and accessing the property

We add the property by simply accessing it. If it doesn’t exist, it will be automatically added to the class. If it exists, it will access it.

The way you access a property is by referencing it via the this.props property that every component has access to. Notice how we specify this property. We place it inside curly brackets – { and }.

In JSX, if you want something to get evaluated as an expression, you need to wrap that something inside curly brackets. If you don’t do that, you’ll see the raw text this.props.greetings printed out.

Making the component call

Further example

Let’s make another component where we take an array, loop over it, and display the data. Define the component.
We add the nameArray property. Then we use the map function to look over each element in nameArray. We use parameter name and index to display the array data.

and we call the component like so:

output at localhost:3000:

Hello, Batman !!

0, Ricky
1, Vera
2, John
Hello, Superman !!

Source Code

Arrow functions (js)

ref – https://medium.com/@thejasonfile/es5-functions-vs-es6-fat-arrow-functions-864033baa1a
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/

When creating instances, every use of “new” defined its own ‘this’ value, where ‘this’ references the instance. The function defined in the constructor function will point to “this”. However, another function inside of that will not point to “this”.

Say we create a literal object and assign a reference named “Pets” to point to it.

The object has properties “names” and “owner”, and a description function. Let’s analyze how ‘this’ and the arrow functions affect each other.

In JavaScript, the method is a function stored in a property of an object. In our case, we have a function, and its stored in property “description”. When calling the method, “this” becomes the object that method “description” belongs to.

The “this” context in description is referencing the literal object that pets is pointing to. We see this when we log the ‘this’:


{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }

We see the object displayed in the console.

Inside of our description function, let’s say we create another function and have a reference called innerFunc pointing to it. We then execute the reference to the function to call it. You’ll see that the ‘this’ inside of innerFunc is undefined.

The reason why is because the inner function does not have a owner, whereas function description does. Inner function see its surrounding scope as function description, and does not detect an object. Hence innerFunc’s this is undefined.

In a more general sense, the solution is that we need to set innerFunc (and our callbacks) up so that it refers to the ‘pets’ literal object.

output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
undefined
— end of innerFunc —
— END OF description —

3 Workaround Solutions

Bind

We use the bind function to bind the pets this to our innerFunc.
Since our function innerFunc’s prototype is Object (as is with any compound objects in JS), we can use the bind function, and pass in the this. We do this inside of description function since description has the correct ‘this’ context.

Once bound, it returns a reference to the innerFunc with the correct this bound. We call that reference as a function and you’ll see that the “this” inside of innerFunc is valid.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

If you want multiple inner functions to work, you’ll have to repeat the binding of this object for each inner function.

Pass as a parameter

We can pass the this into the description function. Due to scope visibility, innerFunc will be able to see and use it.

Multiple inner functions will work also because the parameter is visible to them all.


— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

parent scope local var

Inside description function, we can push a reference called self onto the local stack, and have it point to the this object. Since self is at the parent scope of innerFunc, innerFunc sees self, and can use it.

Multiple inner functions will work because the scope of “self” is visible to them all.


output:

— description —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— innerFunc —
{ names: [ ‘baron’, ‘chief’, ‘axel’ ],
owner: ‘Ricky’,
description: [Function: description] }
— end of innerFunc —
— END OF description —

Fat Arrow

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

An arrow function does not have its own “this”. The “this” value of the enclosing execution context is used. Thus, when using arrow functions inside of standard functions, the “this” within the arrow function will reference its enclosing function.

This works for multiple inner functions.

Arrow functions are best suited for non-method functions

..such as timer functions, array map functions, sync/async functions.
Any kind of functions used inside of calls should be used as arrow functions
because they can correctly find their outer scope’s this.

Arrow functions should not be used as method functions because for literal objects,
they cannot find the “this” to the literal object and will take the “global” this of
{} instead.

For example:

Arrow functions do not have their own this.

Arrow functions cannot be used as constructors and will throw an error when used with new.

Arrow functions do not have a prototype property.

Another Example

Another example is using globally defined functions like setInterval.
setInterval is a function defined in the global object Window and will be bound to that object.
Thus, whenever we call it, and try to use “this” in a function callback, the “this” will be referred to Window.
What we want is to make sure “this” refers to our Person object.

Thus, we have to use arrow function, because arrow function will get the “this” from its surrounding lexical scope.

Prototype and Inheritance in JS (non-class)

https://www.digitalocean.com/community/tutorials/understanding-prototypes-and-inheritance-in-javascript

Creating objects through Constructor Functions

Because each character will share many characteristics, such as having a name, and a level, we use a constructor functions to create templates for those common traits of each hero.

Every hero has a name, and a certain level of experience

We have created a constructor function called Hero with two parameters: name and level. Since every character will have a name and a level, it makes sense for each new character to have these properties.

The this keyword will refer to the new instance that is created, so setting this.name to the name parameter ensures the new object will have a name property set.

The hierarchy looks like this:

The Prototype Object

Whenever we create a constructor function, JS will automatically create a literal object that acts as the prototype object.

That literal object’s sole purpose is to contain functions and properties for all instantiations of your constructor functions.

Note that this object (like all objects of JS) derives from Object, and will have its __proto__ pointing to Object’s Prototype Object.

This literal object acts as the prototype object for Hero. It will also have a constructor property pointing back to your constructor function. Thus, making this prototype object the same type as your constructor function.

In our case, we create a constructor function “Hero” with its properties. JS gives us an empty literal object (Let’s call it Prototype Object) in order to act as a single object that keeps properties and functions that are shared among all instances of Hero.

Note that our Hero Prototype Object derives from Object and thus, has its __proto__ referencing Object’s Prototype Object.

It then creates and assigns a “constructor” property from the Hero Prototype Object to your constructor function. This makes the prototype object type Hero. Finally, it assigns the “prototype” property from your constructor property onto the “Hero Prototype Object”.

Creating an Instance

What this means is that any instantiations of Hero will have its OWN properties and functions from the Constructor function.

hence if we were to make three hero objects, hero1, hero2, and hero3, they all have their own unique properties of name, and level.

i.e

hero1 is “Grom”, level 1
hero2 is “Haomarush”, level 2
hero3 is “Thrall”, level 8

However, they ALL share the “Hero Prototype object”.

So if the “Hero Prototype object” has a property “nickname” initiated to “Orc”, then they would all have nickname = “Orc”.

Same goes for any functions and other properties that “Hero Prototype Object” may have.

Let’s check on how this works. First we display the prototype of our object hero1. You can do it in 2 ways:


output:

Hero {}
Hero {}

Now repeat with hero2, hero3. You’ll see that their __proto__ all are Hero{}. They all point to the same Prototype Object Hero{}

Adding to the Prototype

Let’s add a property nickname to the prototoype, and see what it looks like:

Now our “Hero Prototype Object” will look like this:

Hero { nickname: ‘orc’ }

This means that when we try to read a property from a Hero object, say from hero1,
– it will try to look for “nickname” in hero1 first.
– When it does not find it, it will go up the hierarchy into the prototype object, which it will then find.

If you were to change nickname:

You cannot change it from the instantiation

Simply put, don’t confuse yourself when you try to change a property or function of a prototype object.

You cannot change it through an instantiation like this:

Erroneously, many people may think that it will see if nickname exist in the instantiation, it does not. Then it goes up to the prototype and finds it there. Then it just assigns the new string.

When it comes to setting values, JS does not let you access at the prototype level. It only let’s you read at the prototype level if the property does not exist at the object level.

If you want to set the prototype object to a new value, you must do so through Object.prototype.YourPropertyName.

All of our heroes must be able to greet amicably. Let’s create a function to do so:

Now, all heroes will be able to say hello.

Different character classes of heroes

However, each hero has different abilities. Some wield different weapons. All have vastly different skills and abilities.

It wouldn’t make sense to put all the abilities for every class into the Hero constructor, because different classes will have different abilities.

We want to create new constructor functions, but we also want them to be connected to the original Hero.

Let’s take a look at how we can accomplish this with prototype inheritance and constructors.

The Warrior

We use call in order to chain constructors. Essentially, call replaces a function’s this reference to a passed in object.
Hence, we replace Hero’s constructor function’s this reference to point to Warrior’s this. Then, any kind of initialization done in Hero will take place in Warrior. In other words:

  • We first create a constructor function called Warrior. This identifies Warrior.
  • We then pass the “this” reference to Hero via function call. Using Warrior’s “this” reference, we start to construct it like a Hero. Essentially, we are doing chain constructors for Warrior. We want to first initialize Warrior to be a Hero with Hero’s properties and functions.
  • Then, we come back to Warrior, and initialize Warrior’s properties.

note: The JavaScript call() Method

The call() method is a predefined JavaScript function method.

It can be used to invoke (call) a function with an owner object as the first argument (parameter).
In our example, instance person calls fullName. However, fullName’s this is myObject.

With call(), you can use a method belonging to another object.

This example calls the fullName function of person, but is using it on myObject:

In the extended object Warrior, we initialize Warrior with Hero’s properties via javascript’s call function.

So in the same way, we call Hero’s constructor, but with Warrior’s this.
We pass Warrior’s this into Hero’ constructor

The Healer

Same as Warrior.

Both constructors of Warrior and Healer now have the properties of Hero and their own unique ones.

We’ll add the attack() method to Warrior because its what they do. We want all instances of Warrior to be able to attack, as they should.

All instances of Healer should be able to heal, because its their specialty. Thus, we create the “heal” function so that all future instances of Healer will be able to call heal.

Linking up the Prototype

When you create Warriors, it will be setup in a similar fashion like Hero. You’ll get a Warrior Prototype Object. Your Warrior’s prototype reference will point to Warrior Prototype Object. Warrior Prototype Object will add and point “constructor” back to your Warrior.

Since Hero’s prototype properties and methods are not automatically linked when you use call() to chain constructors, our Warrior will use Object.create() to link the prototypes, making sure to put it before any additional methods are created and added to the prototype like so:

Note:
The Object.create() method creates a new object, using an existing object to provide the newly created object’s __proto__

Object.create

We have class names’s prototype point to a literal object to denote that all
all instances of this class’s __proto__ should point to this literal object
for prototype functionalities. Since Warrior’s prototype now points to literal object
w (which also has __proto__ pointing to Hero Prototype object), this means all instances
of warriors have prototype functionalities on w, and if not found, goes to Hero Prototype Object.

That is why greet will work.

Take note that variable w is the Prototype Object for Warrior. Its pointing to Prototype Object Hero. Hence,

Prototype objects are simply single objects linked together by __proto__. In other words, the Prototype Object A chains to Prototype Object B via Object.create(…). Object.create(…) creates a new object, using an existing object to provide the newly created object’s __proto__ .

When their instances of their classes do not find it i the object, it goes to the prototype object. If it doesn’t find it in that prototype object, it will try to access prototype object’s __proto__, going up the chain.

Now, all instances of Warrior can not only attack, but also greet you as well! Because greet is a prototype function of Hero.

Double Prototype Level

Now let’s create a special class called Mage, where we can heal like a Healer, but also have our own Mage special ability.

Structure

You’ll see that an instance of the Mage will inherit properties and functions of its deriving object Warrior, and its deriving object Hero, and Object.

Furthermore, it will be able to use the whole hierarchy of its own prototype, which includes Warrior, Hero, and Object.


— Structure —

Mage {
name: ‘Thrall’,
level: 99,
weapon: ‘Ragnorak’,
special: ‘summons Bahamut’ }

Mage { constructor: [Function: Mage] }

Healer { constructor: [Function: Healer], heal: [Function] }

Hero { greet: [Function] }

{}

Custom Example

Image Object diagram

output:

Image railay-beach, accessible at: http://localhost:8080/railay-beach.jpg. Created at Fri Apr 13 2018 18:12:24 GMT+0800 (CST)
Image tiger-temple-budda, accessible at: http://localhost:8080/budda.jpg. Created at Fri Apr 13 2018 18:12:24 GMT+0800 (CST)
Image { print: [Function] }
Image { print: [Function] }
{}
{}

Pictorial Object diagram

1) Create custom constructor function
2) Create custom Prototype Object via Object.create. This creates an empty object with prototype of your choice.
3) Check by calling base prototype’s function via call().

4) Connect Prototype Object with your custom constructor function.
5) Instantiate, and call base prototype functionalities for testing.


output:
This place is great!
Description should animate from -300 y (off screen) to middle of screen
Image beautiful-place, accessible at: http://locahost:8080/beautiful-place.jpg. Created at Mon Apr 16 2018 11:06:29 GMT+0800 (CST)


Image southpaw, accessible at: localhost:8080/southpaw.jpg. Created at Mon Apr 16 2018 11:06:29 GMT+0800 (CST)
cover format depending on fashion, fitness, food

CoverArticle object diagram

Workout and Boxing example for JS prototype and class

Workout

First we have the Workout function class. Its declaration acts as the constructor.
We have three properties: title, datetime, and notes.

Setting the Prototype to a object literal

First, let’s define the function class Boxing. We will instantiate it, and pass it for Workout.prototype to point to.

set Workout’s prototype to a Boxing literal object

Now, the hierarchy looks like this:

All instantiation of Workout will share that literal object of type Boxing.

note:

The reason why we have a constructor property from var b is because var b (new Boxing) is the object for Workout Prototype. Thus, even though Workout is using a Boxing literal object to represent for its prototype functionality, its purpose is to be that of the Workout Prototype.

Thus, if we are to have a constructor property pointing back to Workout, any future instantiations of Workout will correctly show Workout, instead of Boxing.


output:

Workout {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function],
constructor: [Function: Workout] }
Workout {
title: ‘Monday Workouts’,
datetime: 2018-02-05T10:11:41.560Z,
notes: ’10x calisthentics’,
setNotes: [Function],
display: [Function] }

Getting property for object with prototype

Instantiate Workout and Get a property

1) Instantiate a Workout object. It basically creates an object from our definition of Workout.

2) Then let’s try using the setNotes function.

We pass in the string to newNote. In the function the ‘this’ evaluates to our Workout instantiation. We check to see if property ‘notes’ exist in Workout. It does, and we set it to our string.

We can log properties of Workout like so:


output:
boxing workout #38
2018-02-05T03:37:56.585Z
100 rounds of sparring

We then come back out to main. Since our prototype is set to Boxing object literal, let’s see what happens when we try to access property coach.

It displays the string “Joel”.

  • First, it will see if the property “coach” exists in the Workout object. It does not.
  • Because it does not, it will go to its prototype and check there.
  • The prototype object is Boxing. And Boxing does have “coach” property initiated to Joel.

Hence, “Joel” is displayed.

Keep in mind that all instantiations will share this Boxing object literal.
If we were to create another Workout object, it will display the same coach.


output:
boxinglesson1.coach: Joel
boxinglesson2.coach: Joel

Let’s evaluate the prototype to see what it looks like:


Boxing {
price: 883,
coach: ‘Joel’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }

Let’s change the coach property to someone else:

Now, as you can see, we literally changed the prototype’s property to something “Rex”. And this gets reflected to other instantiations has their prototype property set to this object.


output:
Boxing {
price: 883,
coach: ‘Rex’,
friends: [ ‘Allen’, ‘Bundy’ ],
_display: [Function] }


boxinglesson1.coach: Rex
boxinglesson2.coach: Rex

code:

Calling prototype object’s functions

Let’s set the coach property back to Joel

Let’s look at prototype function _display

We must take heed that the this in the function belongs to the instantiated object, NOT the prototype. In our case, ‘this’ is an instantiation of Workout.

Thus, when we try to do something like this.coach, it will first check Workout object to see if it has a property called coach.

Because it does not, it will then go to the prototype and check for a coach property. In our case, it does.

Therefore, in our function, this.coach is valid (Joe) and thus, will display Joel in the function.

You will also notice we check if to see if this.display is a function. The this in question is the instantiation of Workout. Thus, we are asking Workout if it has a display function. It evaluate to true, and thus, we call Workout’s display function.

output
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #38 —
@ approximately : Mon Feb 05 2018 11:43:48 GMT+0800 (CST), you will be doing:
100 rounds of sparring
Workout::display() – Your coach is: Joel
Workout::display() – Your price is: 883
————————–

Setting Properties for Objects with Prototype

When we were getting properties, JS first evaluates your instantiated object. Then if it doesn’t exist, it will go up to the prototype object. If it doesn’t exist there, then it will return undefined.

When we’re setting properties, its much more limited. Due to all instantiations share a common prototype object

we cannot set/change a prototype property through an instantiation of an object.

The only way to do is through accessing the prototype object itself like so:

Then, all instantiations of Workout will have prototype property coach “Katu”.

If you were to try to set a prototype property like this:

At first, you may think you have successfully set the prototype’s coach property.


output
—————-Boxing::_display()————–
Your cost: 883
You will be coached by: Sismundo
~~~ Boxing workout # 2 / 24
Boxing::_display() – display() function declared
— Workout::display(): boxing workout #12 —
@ approximately : Mon Feb 05 2018 11:58:22 GMT+0800 (CST), you will be doing:
Run 10 kms
Workout::display() – Your coach is: Sismundo
Workout::display() – Your price is: 883
————————–

But upon closer inspection, you’ll see that instantiations DO NOT allow you to set its prototype’s properties.

Instead, because you try to set a property that does not exist at the instantiation level, it will add the property for you. In our example, it added property coach to your Workout instantiation.