Node JS

Part 2 : JSETTING SKILLS

 JSETTING SKILLS PART 2

  1. Events & Queue
  2. Asynchronization and promises
  3. Classes and OOP

1. Events & Queue

What is STACK ?

The stack is a functionality in the Javascript runtime. Which is an order data structure that keeps track of functions invocations. 

1. Events & Queue

STACK example

function multiply(a,b){
  return a*b;
}
multiply(10,20);

multiply

Main

1. Events & Queue

Set time out 

// run some Instruction after set of time
setTimeout(() => {
  console.log("5 second passed");
}, 5000);
// run some Instruction every a set of time
setInterval(() => {
  console.log("2 seconds passed again");
}, 2000);

Set Interval

1. Events & Queue

Stop Interval

//Stop Interval
var interval = setInterval(specialFunction, 2000);
clearInterval(interval);

Queue

// how Queue handles Events loop
console.log("Start");
setTimeout(() => {
  console.log("0 seconds passed");
}, 0);
console.log("End");

1. Events & Queue

QUEUE example

console.log("Start");
setTimeout(() => {
  console.log("0");
}, 0);
console.log("End");

Stack

Queue

Time fun

Time fun

Main

2. Asynchronization and promises

Promises definition

A promise is an object that represents a task that will be completed in the future.

 

Analogy : picking a ticket to be served at a bank. the ticket you have got is the promise. the service that you will get later is the invocation of the callback in the promise.

2. Asynchronization and promises

Promises architecture

2. Asynchronization and promises

Creating Promises

// creating a promise
const myTicket = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("how can we serve you Sir ?");
  }, 300);
});
console.log(myTicket);

2. Asynchronization and promises

Handling Promises (then)

// Handling promise
const nextInteraction = myTicket.then((response) => {
  console.log(response);
});

Chaining Promises (then)

// chaining then
nextInteraction.then(() => {
  console.log("I would like to transfer some money 🎟 !");
});

2. Asynchronization and promises

Rejecting a promise

// Rejecting a promise
var tickets = 10;
const myTicket1 = new Promise((resolve, reject) => {
  if (tickets > 0) {
    setTimeout(() => {
      resolve("how can we serve you Sir ?");
    }, 300);
  } else reject("No more Tickets");
});

2. Asynchronization and promises

Catching a rejection

// Catching A rejection
myTicket1
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

2. Asynchronization and promises

Final handling of a promise

// Final handling of a promise
myTicket2.finally(() => {
  console.log("We are going out of the bank");
});

2. Asynchronization and promises

Promise all

// Promise All
Promise.all([Ticket1, Ticket2, Ticket3])
  .then((arr) => {
    for (const elm of arr) console.log(elm);
  })
  .catch(console.error);

2. Asynchronization and promises

Async function

A special kind of function that is created using the word async.

the purpose of async functions is to simplify writing asynchronous code, specifically Promises.

2. Asynchronization and promises

Async function

// Async function
async function GetTicket(ticket) {
  if (ticket > 0) return "Here, get a ticket."; // resolve()
  else throw new Error("No Ticket left"); // reject()
}

2. Asynchronization and promises

Async function are promises

// Handling async function
var tickets = 5;
GetTicket(tickets--).then(console.log).catch(console.error);
GetTicket(tickets--).then(console.log).catch(console.error);
GetTicket(tickets--).then(console.log).catch(console.error);
GetTicket(tickets--).then(console.log).catch(console.error);
GetTicket(tickets--).then(console.log).catch(console.error);
GetTicket(tickets--).then(console.log).catch(console.error);// error

2. Asynchronization and promises

await in Async function

async function GetTickets(ticket) {
  Tickets = [];
  while (ticket > 0) {
    Tickets.push(await GetTicket(ticket--));
  }
  return Tickets;
}
GetTickets(tickets).then((Tickets) => {
  console.log(Tickets);
});

3. Object Oriented Programing

Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.

3. Object Oriented Programing

Objects

What is an object ?

  1. a material thing that can be seen and touched.
  2. a person or thing to which a specified action or feeling is directed.

Example :

3. Object Oriented Programing

What is a class ?

a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.

What is a class in OOP?

is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). The user-defined objects are created using the

class MyClassName{
	//our Code
}

How to use the class key word.

Classes

3. Object Oriented Programing

class Bottle {
  bottomRadius = 2.5;
  height = 12;
  capRaduis = 1;
  neckRaduis = 1.5;
  capacity = 1.5; //Liter
  filledPercentage = 0;
}

Attributes

3. Object Oriented Programing

class Bottle {
  bottomRadius = 2.5;
  height = 12;
  capRaduis = 1;
  neckRaduis = 1.5;
  capacity = 1.5; //Liter
  filledPercentage = 0;
  //methods
  fillBottle(amount) {
    this.filledPercentage += ((amount * 100) / capacity) % 100;
  }
  waterSpill(amount) {
    this.filledPercentage -= ((amount * 100) / capacity) % 100;
  }
}

3. Object Oriented Programing

Constructor & new

What is a constructor ?

Not this one

A constructor is a special method that is used to initialize a newly created object to desired values or default values just after the memory is allocated for it.

class Bottle {
  bottomRadius;
  height;
  capRaduis;
  neckRaduis;
  capacity;
  filledPercentage;
  //constructor
  constructor() {
    this.bottomRadius = 2.5;
    this.height = 12;
    this.capRaduis = 1;
    this.neckRaduis = 1.5;
    this.capacity = 1.5;
    this.filledPercentage = 0;
  }
  //the rest of the methods
}

Important !!!
the constructor can only be declared using the word constructor.

3. Object Oriented Programing

Constructor & new

how to use the Constructor ?

ClassName varName = new ClassName();

The word new is the one who calls the Constructor to create the object or what we Call an Instance.

const bottle = new Bottle();

Example

3. Object Oriented Programing

this

this is used to let the computer knows the variable name you are using belongs to this Instance.

class Bottle {
  bottomRadius = 2.5;
  height = 12;
  capRaduis = 1;
  neckRaduis = 1.5;
  capacity = 1.5; //Liter
  filledPercentage = 0;
  //methods
  fillBottle(amount) {
    this.filledPercentage += ((amount * 100) / capacity) % 100;
  }
  waterSpill(amount) {
    this.filledPercentage -= ((amount * 100) / capacity) % 100;
  }
}

We can see that we have capacity as a parameters and as an attribute. so to make the difference we use the word this to show the program which one belongs to the object.

3. Object Oriented Programing

what is Inheritance ?

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones and forming them into a hierarchy of classes

The definition of inherit is to receive something, such as money, an asset, or a problem or characteristic from someone else. An example of inherit is when you born you take the characteristics of your parents.

3. Object Oriented Programing

what is Inheritance ?

class Animals {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    sing() {
        return `${this.name} can sing`;
    }
    dance() {
        return `${this.name} can dance`;
    }
} 
class Cats extends Animals {
    constructor(name, age, whiskerColor) {
        super(name, age);
        this.whiskerColor = whiskerColor;
    }
    whiskers() {
        return `I have ${this.whiskerColor} whiskers`;
    }
}
var clara = new Cats("Clara", 33, "indigo");

3. Object Oriented Programing

What is an Access modifier ?

Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members.

3. Object Oriented Programing

public access

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

class Animal{
  Name;
}

3. Object Oriented Programing

private access

The type or member can be accessed only by code in the same class or struct.

class Animal{
  #Name;
}

JSKILLS

Part 2

Ends

Node js Chapter 2 Part 2

By Youcef Madadi

Node js Chapter 2 Part 2

  • 327