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.
Understanding Callback
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.
- <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");
- </script>
In the notifyall() method, shown above, the notification happens by sending SMS and by sending an Email. Hence, the invoker of the notifyAll method has to pass two functions as parameters, each function is doing a single responsibility like sending SMS and sending an Email.
The output of the script would be,
starting notification process
Sms send ..
email send ..
End of script
In the code, mentioned above, the function calls are synchronous. It means the UI thread would be waiting to complete the entire notification process. Synchronous calls become blocking calls. Let's understand non-blocking or async calls now.
Understanding AsyncCallback
Consider the above example.
To enable the script, execute an asynchronous or a non-blocking call to notifyAll() method. We shall use the setTimeout() method of JavaScript. This method is async by default.
The setTimeout() method takes two parameters,
- 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");
- </script>
Output
End of 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>
ES6 comes to your rescue by introducing the concept of promises. Promises are "Continuation events" and they help you to execute the multiple async operations together in a much cleaner code style.
Let's understand this with an example.
Syntax is given below:
- var promise = new Promise(function(resolve , reject){
-
-
- if()
- resolve("stuff worked");
-
- else
- reject(Error("It broke"));
-
- });
-
- return promise;
The first step towards implementing the promises is to create a method that will use the promise. Let’s say in this example, the getSum() method is asynchronous i.e. its operation should not block other methods’ execution. As soon as this operation completes, it will later notify the caller.
The below given example (Step 1) declares a Promise object ‘var promise’. The Promise Constructor takes to the functions first for the successful completion of the work and another in case an error happens.
The promise returns the result of the calculation by using the resolve callback and passing in the result i.e. 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 second step details the implementation of the caller (STEP 2).
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
11
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);
- },
- function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- }, function(error)
- {
- console.log(error);
- });
Output
11
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);
- },
- function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- returngetSum(30, 40);
- }, function(error)
- {
- console.log(error);
- })
- .then(function(result)
- {
- console.log(result);
- }, function(error)
- {
- console.log(error);
- });
- console.log("End of script ");
- </script>
Output
The program displays ‘end of script’ first and then results from calling getSum() method, one by one.
End of script
11
30
70
This shows getSum() is called async style or non blocking style . Promise gives a nice and clean way to deal with the Callbacks.