JavaScript Promises - ECMASCRIPT 6

In this tutorial, you will learn the following in order:

  • Callback functions
  • Evolution of callback functions - promises
  • How to configure ECMASCRIPT 6 promises
  • How to create a simple promise and them move on to more advanced ones
  • How to chain a series of promises for a final outcome
  • How to use promise.all()
  • How to use promise.race()
  • How to generate the famous Fibonacci Sequence with promises

Finding a good book to master promises is certainly not promising: there are so many around - most with eye-catching titles and very complex substance.
Therefore, Vivax Solutions recommends this book for those who really want to delve into JS-Promises.
Please click the image to access Amazon:

Callback Functions - stepping stones to promises

It's not a classic egg-or-chicken-first case; it's callback function that preceded JavaScript promises. A callback function acts as a parameter to another function. In the following example, function defined in variable clbIn is a callback function for function clbMain() - the main function.

function clbMain(callback){
  var x=Math.round(Math.random()*10+1);
  if (x%2==0){
   let t=true;
   callback(t)
  }
  else{
   let t=false;
   callback(t)
  }
}
var clbIn =function callback(q){
 if (q==true){
  document.getElementById('showing').innerHTML="It's an even number. "
 }
 &else{
  document.getElementById('showing').innerHTML="It's not an even number. "
 }
}

If you keep clicking the button, the callback function at work can be seen.

 

You may have noticed that callback is a function that takes a parameter. So, when you use it in the main function as the callback, the parameter must be included, which can create more confusion. In order to get round this, the callback function is defined as a variable - clbIn. So, it's just a 'letter' when it comes to using in the main function.

Now just imagine, you are going to include a few callback functions inside the main function. It can get complicated, though.

 

Advanced callback functions

The following example uses two callback functions to convert a given temperature to Celsius or Fahrenheit.

function tempConverter(x,callback){
  x=document.getElementById('temp').value;
  document.getElementById('show').innerHTML="Temp: " +callback(x);
}
var c=function toCelsius(x){
 return ((Math.round((x-32)*5/9*10)/10))+"0";
}
var f=function toFahrenheit(x){
 return ((Math.round(((x*9/5)+32)*10)/10))+"0";
}
  

 

JavaScript Promises

With the introduction of promises in ECMASCRIPT6, the JavaScript community can ultimately breathe a sigh of relief by turning their back on Callback Hell - the messy situation developers get into with too many callback functions. The following tutorial is designed to give would-be learners as well text-muted as developers an opportunity to grasp the concept easily.

The Structure of a Promise

The following promise checks whether a generated random number is odd or even; if it's even, it resolves;otherwise, it rejects. The structure of a promise as follows:

var number = Math.round(Math.random()*20+1);
var promise =new Promise(function(resolve, reject){
 if (number%2===0){
  resolve('Resolved! Here is the even number: '+number)}
 else{
  reject('Rejected! Not an even number.')}
});

In order to use the promise, the following code has to be used:

return promise
.then(function(number){
console.log("It's an even number; promise resolved. The number is " + number);
})
.catch(function(error){
console.log("It's an odd number; promise rejected; the error " + error);
});

The first example shows how it works. please follow all the examples; if you are a novice, they will make a big difference.

The code samples of the these promises are on GitHub as a repository.

1 Resolves with an even Number

When you click on the button, a random integer is generated; if it is an even number, the promise is resolved; otherwise, promise is rejected.

Please click on the button a few times, in order to see this at work.



 

GitHub

 

2 Promise Chaining - calculating standard deviation

In this case, promise chaining works as follows:

  1. Five random numbers are generated - promise 1.
  2. The total of five numbers calculated - promise 2.
  3. The mean of the numbers is calculated - promise 3.
  4. The variance of the numbers is calculated - promise 4.
  5. The standard deviation of the numbers is calculated - promise 5.

Please click on the button a few times, in order to see this at work.



 

GitHub

 

3 Promise.all()

In this case, promise.all() works as follows:

  1. A number is given by a user.
  2. Checking whether it's a multiple of 3 - promise 1.
  3. Checking whether it's a multiple of 4 - promise 2.
  4. Checking whether it's a multiple of 5 - promise 3.
  5. Only when all three promises resolve, is it a success; otherwise, they reject - a failure.

Please enter a number like, 12, 30, 60, 120, 2400 etc., into the text box a few times, in order to see this at work.



 

GitHub

 

4 Promise.race()

In this case, promise.race() works as follows:

Three different random numbers are generated by three different promises. The one that gets the first even number wins the race! Please keep pressing the button; if all promises reject, you will see a blank screen.



 

GitHub

 

5 Generating Fibonacci Sequence

This is an interesting case of promise chaining. it works as follows:

Enter two numbers into the text boxes as initial values; the promise generates the next four numbers. If you want, you can add more elements to the promise to generate a long sequence; the sky is the limit!



 

GitHub

 

 

 

 

Recommended Reading

Amazon Best Seller

 

Everything is evolving; so is the layout of a text book. By uniquely presenting the rich contents of the book, the author has elevated positive user experience of reading a text book to a new level: the examples are easy to follow and rich in standard. Highly recommended for those who want to master JavaScript and JQuery.

Progressive Web Apps(PWA)


 

The significance of app stores is over; progressive web apps is the next big thing. They are just websites that makes the need of going through app stores and need of storing redundant. They work offline too. If you have a reasonable understanding of HTML, CSS and JavaScript, this is the book for you to learn in no time.

HTML5 Canvas Animations


 

David Geary, in this book, shows how to combine JavaScript and HTML5 Canvas to produce amazing animations; he has set aside a whole chapter to teach you the role of physics in animations. If you want an in-depth understanding about HTML5 Canvas animations, this is a must read.