Node.js

Node.js

·

4 min read

ES6

What is ES6?

  • ECMAScript 6 is called ES6.

What is ECMAScript?

  • It is a standard syntax of Javascript.
  • Many modern syntax as been added to Javascript After ECMAScript version 6.

Why do we have to use ES6?

  • Modern syntax helps us with productivity improvement.
  • Node.js is supporting recent ECMAScript.
  • It is important to learn useful modern syntax and utilize the syntax in an appropriate way.

Node.js and ES6 Relationship

  • Not all syntax of ES6 are not supported in Node.js.

let, const

ES5

// Variable and Constant are not distinguishable in syntax
var TITLE = "NODE.js";
var director = "elice";
director = "rabbit";
TITLE = "ES6"; // no error

ES6

// We can distinguish constant and variable in syntax
const TITLE = "NODE.JS";
let director = "elice";
director = "rabbit";
TITLE = "ES6" // error

Templete String

ES5

var name = "elice";
var age = 5;
// We need "\n" to break line
// We also have to concatenate string with variable using +
var hi = `My name is `
  + name
  + '.\n I\'m'
  + age
  + 'years old.';

ES6

const name = "elice";
const age = 5;
// Easy line break.
// variable use is also easy
const hi =
`My name is ${name}.
I'm ${age} years old`;

Arrow Function

ES5

// function declaration
function doSomething(param) {
  console.log("do something");
}

// ananymous function
setTimeout(function(param) {
  console.log("no name function");
}, 0)

// We can declare same named function again
function doSomething () {
  console.log("do other");
}

ES6

const doSomething = (param) => {
  console.log("do Something");
}

setTimeout((param)=> {
  console.log("no name function");
},0);

doSomething = () => {
  console.log("do other");
}

Class

ES5

function Model(name, age){
  this.name = name;
  this.age = age;
}

Model.prototype.getInfo = function() {
  console.log(this.name, this.age); 
}
var model = new Model("elice", 5);
model.getInfo();

ES6

class Model {
  constructor (name, age){
    this.name = name;
    this.age = age;
  }

  getInfo() {
    console.log(this.name, this.age)
  }

}
const model = new  Model("elice", 5);
model.getInfo();

Destructing

ES5

var obj = {name:"elice", age:5};
var name = obj.name;
var age = obj.age;

var arr = ["some","values"];
var first = arr[0];
var second = arr[1];

ES6

const obj = {name:"elice", age:5};
const {name, age} = obj;
const {name : n1, age : a1} = obj;
const arr = ["some", "values"];
const [first, second] = arr;

Asynchronous Coding

What is Asynchronous Coding?

  • It is a way to implement asynchronous even driven operations.
  • There are 3 ways to implement Asynchronous operations in Node.js

What is 3 ways for Asynchronous coding in Node.js?

Callback

db.getUsers((err, users)=>{
  console.log(users);
});

// Callback hell
db.getUsers((err, users) =>{
  if(err) {...return;}
  async1(users, (r1) =>{
    async2(r1, (r2) =>{
      async3(r2, (r3) =>{
        ...
      });
    });
  });
})
  • Traditional way for event driven implementation

Promise

db.getUsersPromise().then((users) =>{
  returnpromise1(users);
  })
  .then(r1 =>promise2(r1))
  .catch(...);

function getUsersPromise(params) {
  return newPromise((resolve, reject)=>{
    getUsers(params, (err, users) =>{
      if (err) {
        reject(err);return;
      }
      resolve(users)
    ;})
  ;})
;}

// promise hell can be also happened...
promise1().then(r1 => {
  return promise2(r1)
  .then(r2 =>promise3(r1, r2))
  });
  • Asynchronous coding that makes up for the callback's disadvantages.
  • We can omit return when There is only one line inside of a brace.
  • When error occurs, promise executes .catch.
  • When promise3 function needs results from 2 other functions, promise hell might also be happened.

Aync-Await

async function doSomething() =>{
  cosntr1 = awaitpromise1();
  constr2 = awaitpromise2(r1);
  constr3 = awaitpromise3(r1, r2);
  ...
  returnr3;
});

doSomething().then(r3 =>{
  console.log(r3)
});
  • It is another syntax of promise
  • We can get result from promise function by using await in async function.
  • Until promise function using await is completed, interpreter doesn't go to next line.
  • return of async function is promise function.
  • Asynchronous coding that makes up for the promise's disadvantages.

Promise and Async function error handling

// promise error handling
function doSomething(msg) {
  return promise1()
    .then(r => {
      console.log(r)
    })
    .catch(e => {
      console.log(e)
    });
}


// async error handling
async function doSomething(msg){
  try {
    const r = await promise1();
    console.log(r);
  } catch(e) {
    console.error(e);
  }
}

Promise parellel execution

// This function is going to take 3 sec..
async function sync() {
  constr1 = await promise1(); // Let's say this takes 1 sec.
  constr2 = await promise2(); // Let's say this takes 2 sec.
  console.log(r1, r2);
}
---

// This function is going to take 2 sec...
async function parallel() {
  const[r1, r2] = await Promise.all([promise1(),promise2(),]); // 1 sec and 2 sec in parellel
  console.log(r1, r2);
};

In Concolusion

  • We prefer async-await. It's because this syntax has a good readability
  • But legacy code could be in promise or callback. So we need to be able to implement all of them in an appropriate way.

Did you find this article valuable?

Support Junho Dev Blog by becoming a sponsor. Any amount is appreciated!