Introduction
Promises are a clean way to implement async programming in JavaScript (ES6 new feature). Prior to promises, Callbacks were used to implement async programming. Let’s begin by understanding what async programming is and its implementation, using Callbacks.
A function may be passed as a parameter to another function. This mechanism is termed a Callback. A Callback would be helpful in events.
The following example will help us better in understanding this concept.
Understanding Callback
- <script>
- function notifyAll(fnSms, fnEmail)
- {
- console.log('starting notification process');
- fnSms();
- fnEmail();
- }
- notifyAll(function()
- {
- console.log("Sms send ..");
- }, function()
- {
- console.log("email send ..");
- });
- console.log("End of script"); //executes last or blocked by other methods
- </script>
Sms send ..
email send ..
End of script
Understanding AsyncCallback
- A callback function and
- The no. of seconds after which the method will be called.
In this case, the notifications process has been wrapped with timeout. Hence, it will take a two seconds delay, set by the code. The notifyAll() will be invoked and the main thread goes ahead like executing other methods. Hence, the notification process will not block the main JavaScript thread.
- <script>
- function notifyAll(fnSms, fnEmail)
- {
- setTimeout(function()
- {
- console.log('starting notification process');
- fnSms();
- fnEmail();
- }, 2000);
- }
- notifyAll(function()
- {
- console.log("Sms send ..");
- }, function()
- {
- console.log("email send ..");
- });
- console.log("End of script"); //executes first or not blocked by others
- </script>
starting notification process
Sms send ..
email send ..
In case of multiple callbacks, the code will look scary.
- <script>
- setTimeout(function()
- {
- console.log("one");
- setTimeout(function()
- {
- console.log("two");
- setTimeout(function()
- {
- console.log("three");
- }, 1000);
- }, 1000);
- }, 1000);
- </script>
- var promise = new Promise(function(resolve , reject){
- // do a thing, possibly async , then..
- if(/*everthing turned out fine */)
- resolve("stuff worked");
- else
- reject(Error("It broke"));
- });
- return promise; // Give this to someone
- resolve(n1 + n2);
If the getSum() encounters an error or an unexpected condition, it will invoke the reject callback method in the Promise and pass the error information to the caller.
- reject(Error("Negatives not supported"));
The method implementation is given below (STEP 1).
- function getSum(n1, n2)
- {
- varisAnyNegative = function()
- {
- return n1 < 0 || n2 < 0;
- }
- var promise = new Promise(function(resolve, reject)
- {
- if (isAnyNegative())
- {
- reject(Error("Negatives not supported"));
- }
- resolve(n1 + n2);
- });
- return promise;
- }
The caller should use the ‘then’ method, which takes two callback methods- first for success and second for failure. Each method takes one parameter, as shown below:
- getSum(5, 6)
- .then(function (result) {
- console.log(result);
- },
- function (error) {
- console.log(error);
- });
Output
Since the return type of the getSum() is a Promise, we can actually have multiple ‘then’ statements. The first 'then' will have a return statement.
- getSum(5, 6)
- .then(function(result)
- {
- console.log(result);
- returngetSum(10, 20); // this returns another promise
- },
- function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- }, function(error)
- {
- console.log(error);
- });
30
The example given below issues three then() calls with getSum() method.
- <script>
- function getSum(n1, n2)
- {
- varisAnyNegative = function()
- {
- return n1 < 0 || n2 < 0;
- }
- var promise = new Promise(function(resolve, reject)
- {
- if (isAnyNegative())
- {
- reject(Error("Negatives not supported"));
- }
- resolve(n1 + n2);
- });
- return promise;
- }
- getSum(5, 6)
- .then(function(result)
- {
- console.log(result);
- returngetSum(10, 20); //this returns another Promise
- },
- function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- returngetSum(30, 40); //this returns another Promise
- }, function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- }, function(error)
- {
- console.log(error);
- });
- console.log("End of script ");
- </script>
11
30
70

Santhakumar MunuswamyPosted Jun 30, 2016, 12:56 AM
Thank you for nice article