Callbacks, promises, Async and Await

 

Supriya

Callbacks:

A callback is a function which is passed as a parameter to another function

document.getElementById('button').addEventListener('click', () => {
  //item clicked
})
function first(){
  console.log(1);
}

function second(){
  console.log(2);
}

first();
second();
function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 5000);
}

function second(){
  console.log(2);
}

first();
second();
setTimeout(() => {
  
//   all the statements in here are 
//   run after 2 seconds

}, 2000)
function funName (param1, param2, otherFunction){
  console.log("Inside : funName");
  console.log(param1);
  console.log(param2);
  otherFunction();
  console.log(param1 + param2);
}

function multiplyTwoNumbers(){
  console.log("Inside : multiplyTwoNumbers");
  console.log(23*78);
}

function subtractTwoNumbers(num1,num2){
  console.log("Inside : subtractTwoNumbers");
  console.log(num1-num2)
}

funName(12,3,multiplyTwoNumbers);
creating callbacks: 
function funName (param1, param2, otherFunction){
  console.log("Inside : funName");
  console.log(param1);
  console.log(param2);
  otherFunction(param1,param2);
  console.log(param1 + param2);
}

function multiplyTwoNumbers(){
  console.log("Inside : multiplyTwoNumbers");
  console.log(23*78);
}

function subtractTwoNumbers(num1,num2){
  console.log(`num1: ${num1} \nnum2: ${num2}`)
  console.log("Inside : subtractTwoNumbers");
  console.log(num1-num2)
}

funName(12,3,subtractTwoNumbers);
passing parameters to callbacks 
Without callbacks:
let posts = [
  {
    "title" : "How to stay hydrated",
    "body" : " Drink water"
  },
  {
    "title" : "COVID-19",
    "body" : "Stay at home"
  }      
  ];

function createPost(post){
  setTimeout(function(post){
    posts.push(post);
  }, 2000)
}

function getPosts(){
  setTimeout(function(){
    let op = "";
    posts.forEach(function(post){
      op += `<li> ${post.title} </li>`
    });
    document.body.innerHTML = op;
  },1000);
}

createPost({"title" : "not today", "body" : "blah-blah-blah"});
getPosts();
With callbacks:
let posts = [
  {
    "title" : "How to stay hydrated",
    "body" : " Drink water"
  },
  {
    "title" : "COVID-19",
    "body" : "Stay at home"
  }      
  ];

function createPost(post, callback){
  setTimeout(function(post){
    posts.push(post);
    callback();
  }, 2000)
}

function getPosts(){
  setTimeout(function(){
    let op = "";
    posts.forEach(function(post){
      op += `<li> ${post.title} </li>`
    });
    document.body.innerHTML = op;
  },1000);
}

createPost({"title" : "not today", "body" : "blah-blah-blah"}, getPosts);

Disadvantages of callbacks :

  • Every callback adds a level of nesting
  • When you have lots of callbacks, the code starts to be complicated very quickly
window.addEventListener('load', () => {
  document.getElementById('button').addEventListener('click', () => {
    setTimeout(() => {
      items.forEach(item => {
        //your code here
      })
    }, 2000)
  })
})

This is just a simple 4-levels code, but I’ve seen much more levels of nesting and it’s not fun.

Alternatives:

  • Promises
  • Async and Await

Promises:

  • They are used to handle asynchronous operations
  • While they are handling asynchronous operations, they can promise to do something, when the operation is finished
  • Response - .then()
  • Reject - .catch()

What's a promise?


var promise = new Promise(function(resolve, reject) { 
  const x = "Let it go"; 
  const y = "Let it be";
  if(x === y) { 
    resolve(); 
  } else { 
    reject(); 
  } 
}); 
  
promise. 
    then(function () { 
        console.log('Success, You are a FREE'); 
    }). 
    catch(function () { 
        console.log('Some error has occured'); 
    }); 
const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
    resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");

How does a promise work?

new Promise((resolve, reject) => {
    console.log('Initial');

    resolve();
})
.then(() => {
    throw new Error('Something failed');
        
    console.log('Do this');
})
.catch(() => {
    console.error('Do that');
})
.then(() => {
    console.log('Do this, no matter what happened before');
});

It's possible to chain after a failure, i.e. a catch, which is useful to accomplish new actions even after an action failed in the chain.

let posts = [
  {"title" : "How to stay Hydrated", "body" : "drink water"},
  {"title" : "COVID-19", "body" : "stay home"}
];

function createPost(post){
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      posts.push(post);
      let error = false;
      if(!error){
        resolve() 
        // calls the function that is defined in .then()
      }else{
        reject() 
        // calls the function that is defined in .catch()
      }
      
    }, 2000);
  })
}

function getPosts(){
  setTimeout(function() {
    let op = '';
    posts.forEach(post => op+= `<li> ${post.tile} </li>`);
  }, 1000)
}

let newPost = {'title' : "Extended Summer break?" , "body" : "nah!"};
createPost(newPost)
.then(getPosts)
.catch(function(err) {
  console.log(err);
});

lets promise ourselves to understand promises

Async and Await

  • It is a part of ES7 or ES2016
  • There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”.
  • It’s surprisingly easy to understand and use
  • We might have to compile down to ES5 using Bable or Webpack

Async :

  • It can be placed before a function.
  • The word “async” before a function means that the function always returns a promise.
  • Other values are wrapped in a resolved promise automatically.
async function f() {
  return "Freedom!";
}

f().then(data => {
  console.log(data)
}); // Freedom!

=

async function f() {
  return (Promise.resolve("Freedom!"));
}

f().then(data => {
  console.log(data);
}); // Freedom!

Await :

  • The keyword await makes JavaScript wait until that promise settles and returns its result. 
  • syntax : let value = await promise;
  • NOTE: await must always be wrapped inside an async function
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  // wait until the promise resolves (*)
  let result = await promise; 

  alert(result); // "done!"
}

f();
async function f() {

  let promise = new Promise((resolve, reject) => {
  console.log("inside : promise");
    if(typeof(34) !== typeof("not today"))
    {
    console.log("condition satisfied");
    setTimeout(() => {
      console.log("this is done after 1 sec")
      resolve("inside : resolve")
      }, 10000);
     }
     else {
      reject("some error T-T");
      }
  });
  // wait until the promise resolves (*)
  let result = await promise; 
  
  return(result); // "done!"
}

f().then(data=> console.log(data))
.catch(err => console.log(err));

That's all folks!

Callbacks, promises, Async and Await

By Supriya kotturu

Callbacks, promises, Async and Await

Asynchronous javascript concepts with control flow

  • 79