Day6

Promise and Arrow Functions

Youtube resources: Promises and Arrow Functions

Resouces: Promises and Arrow Functions

Promises

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

Benefits of Promises

A Promise has four states:

A promise can be created using Promise constructor.

var promise = new Promise(function (resolve, reject) {
  //do something
});

Parameters

Example

var promise = new Promise(function (resolve, reject) {
  const x = "google";
  const y = "google";
  if (x === y) {
    resolve();
  } else {
    reject();
  }
});

promise
  .then(function () {
    console.log("Success, You are a Geek");
  })
  .catch(function () {
    console.log("Some error has occured");
  }); //Output: Success, You are a Geek

Why Promises are better then Callbacks with an example

The Callback Way

function isUserTooYoung(id, callback) {
  openDatabase(function (db) {
    getCollection(db, "users", function (col) {
      find(col, { id: id }, function (result) {
        result.filter(function (user) {
          callback(user.age < cutoffAge);
        });
      });
    });
  });
}

The Promises way

function isUserTooYoung(id) {
  return openDatabase()
    .then(getCollection)
    .then(find.bind(null, { id: id }))
    .then(function (user) {
      return user.age < cutoffAge;
    });
}

Applications

more examples here

Arrow Functions

Arrow functions were introduced in ES6. Arrow functions allow us to write shorter function syntax:

Syntax

//normal function
var hello = function () {
  return "Hello World!";
};

//arrow function
var hello = () => {
  return "Hello World!";
};

It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword.

//arrow functions return value by default
var hello = () => "Hello World!";

//arrow function with parameters
var hello = (val) => "Hello " + val;

more examples here

Excercise

Note: You can solve them anywhere you want if you stuck see the solution. You don’t have to submit the solution to me they are just for your practice.

Questions

Solution

See solutions here