Promises and Callbacks on Javascript With Practical Examples

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started 

A Promise is an object represents the eventual completion (or failure) of an asynchronous operation and its resulting value, which is used instead of callbacks which may be intimidating when being used on your code a lot and in a nasty way.

There are two states of the promise (Resolved or Rejected) resolved simply means that the operation that you have requested has been successfully completed and rejected tells you that there was an error when trying to execute the operation, this way you can use less nested callbacks and make you code structure easier to read through and tidy.

Also, Promises are very beneficial if you are dealing with multiple asynchronous calls and have only one success path, promises can allow you to shrink your async calls by using callbacks in more readable and reusable code structure.

Promise Syntax

The syntax is quite simple.

//Create an Instance using new keyword 
let myPromise = new Promise(  function(resolve, reject) { ... } );
/*It takes a function as a parameter it self takes a resolve and a reject handlers that you use either when the operation goes successfully or when an error happens */

 Then in order to execute the promise, you call it and specify the handlers.

// then and catch methods are equivelante of resolve and catch 
myPromise.then((res) => {
   console.log("Success: ", res);
}).catch((err) => {
   console.log("Error: ", err);
});

So when resolve gets called on the promise definition the then callback is going to be executed passing it the success response, or when it gets rejected (by calling reject) the catch will be executed which receives the err object passed to the reject.

It is actually very simple if you still confused about how it works and the beneficial behind using a promise instead of normal nested callbacks well, the example should make it clear for you.

Working with Promises

Here is a scenario that we are going to use for making clear for you to understand the power of promises.

You have an API Endpoint somewhere (if you are not familiar with APIs, take a look on this Tutorial) where this API gives you access to data saved on the database and you want to get the list of users registered on the database, using a promise.

We are going to use axios Node module for sending HTTP Request.

#Install it first 
npm install axios

Axios itself is built on a promise based methods, which means when you send an HTTP request you will receive a promise that will be either resolved or rejected depending on the state of the request, so you can receive the response.

import axios from "axios";
//We want to get the list of the users whenever we press the button 
let btn = document.getElementsByClassName("btn")[0];

let getUsers = () => {
  //First, send a GET Request to get the users (JSON)
  axios
  .get("https://jsonplaceholder.typicode.com/users")
  .then((res) => {
      //Request success, Response Received!
      console.log("Users: ", res.data);
  })
  .catch((err) => {
      //Error in Request or Server Error
      console.log("ERROR: ", err.message);
  });
};
//On button click get users 
btn.onclick = () => {
   getUsers();
};

If you try to save and refresh the page then press the button you should be able to get the users from the endpoint API successfully using a promise behind the scenes works for you that.

try to mistype the submit URL and you will get an error logged for you (the catch method will be called instead of the then).

This allows you to use fewer callbacks and organize your code structure the way you want it to be beside that it is asynchronous which means the rest of the code is going to be still executed while the promise is still waiting for the response.

Take a look at this example using a delayed resolve promise, in order to see how it actually operates.

let delayedResponse = (delay = 2000) => {
    return new Promise((resolve, reject) => {
        //Delay the response (promise resolve)
        setTimeout(resolve, delay);
    });
};

//The Delay response function returns a promise which means we can use the then or catch methods on the function

//Run it on button click
btn.onclick = () => {
    //The promise will be resolved after 5seconds = 5000ms
    delayedResponse(5000).then(() => {
        console.log("Your Response Has Been Delayed!");
    });
    //Log something to make sure it is async 
   console.log("I'm the first one to get called!");
};

As you can see the response will be received after the delay which means it is asynchronous but you still using it a very simple way.

Here is a sample of the console you that will see once the button is pressed.

/* CONSOLE */ 
I'm the first one to get called!
//After 5seconds 
Your Response Has Ben Delayed!

 

What's Next

Now you can start playing with promises in order to understand it better how it works and the main reason you would prefer a promise over nested callbacks, Also there another ES6 way of dealing with async calls without callbacks which we will cover in the next tutorials (Async/Await).

 

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games