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.
The following example will help us better understand this concept.
The following output is displayed on successful execution of the above code.
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 −
The following 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
Step 1 − 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.
Step 2 − reject(Error("Negatives not supported"));
The method implementation is given in the following code (STEP 1).
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 in the following code.
The program displays ‘end of script’ first and then results from calling getSum() method, one by one.
Understanding Callback
A function may be passed as a parameter to another function. This mechanism is termed as a Callback. A Callback would be helpful in events.The following example will help us better understand 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"); //executes last or blocked by other methods </script>In the notifyAll() method shown above, the notification happens by sending SMS and by sending an e-mail. Hence, the invoker of the notifyAll method has to pass two functions as parameters. Each function takes up a single responsibility like sending SMS and sending an e-mail.
The following output is displayed on successful execution of the above code.
starting notification process Sms send .. Email send .. End of scriptIn 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.
- The number of seconds after which the method will be called.
<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>The following output is displayed on successful execution of the above code.
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 execute the multiple async operations together in a much cleaner code style.
Example
Let's understand this with an example. Following is the syntax for the same.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 someoneThe first step towards implementing the promises is to create a method which 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 following 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
Step 1 − 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.
Step 2 − reject(Error("Negatives not supported"));
The method implementation is given in the following code (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 in the following code.
getSum(5, 6) .then(function (result) { console.log(result); }, function (error) { console.log(error); });The following output is displayed on successful execution of the above code.
11Since 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); });The following output is displayed on successful execution of the above code.
11 30The following example 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>The following output is displayed on successful execution of the above code.
The program displays ‘end of script’ first and then results from calling getSum() method, one by one.
End of script 11 30 70This shows getSum() is called in async style or non-blocking style. Promise gives a nice and clean way to deal with the Callbacks.
No comments:
Post a Comment