Skip to main content

Javascript 106 : Promises

This post is a continuation of "Javascript 105: Callbacks". So If you have not studied the last post please go back and then come back to this. 

As discussed in the last post, a callback is a way to force synchronous (sequential) operation of otherwise asynchronous tasks. Since this is a continuation lets begin from where we left off with the last post. 

Take a look at this code, and its output. 
Output:
 We did that to ensure the statements prints in order

This is okay for situation like this. 

But imagine a code as follows
Output:
Take a look at the code and the output carefully. It is obvious that these statements are printing out of order due to the inherent asynchronous nature of JS. 

If we still want to ensure that they take their own time to execute but still executing the way we want, how do you think that we can make this happen. 

Sure, we can create multiple callback functions and call them inside of each (Which I even do not wish to try), but that will make a very complicated and unmanageable code. That chaotic code style is called "callback hell".  

This is where the "Promises" comes in, which is a more elegant and cleaner approach to this problem.  

A Promise is a way to arrange the operation of asynchronous calls. 

  • The promise takes a single input argument and that is a callback function.
  • That callback function takes two input arguments. "resolve" and "reject"
  • Perform the operation inside the callback function and if it is a success, calls "resolve()"
  • If the operation inside is a failure, it calls the "reject()"
Now lets try to come up with a sample promise to clarify whats this all about. 
Output:
In the above test code I have commented out the five setTimeout() function. We are coming back to it later.
  1. The line 7 to 16 is a simple promise.  The "promiseDemo" variable is assigned with a new Promise object.
  2. The Propmise constructor took two arguments called "resolve" and "reject".
  3. From line 8 to 15 is the operation
  4. I am calling the "resolve" function with the argument "they are equal" if the operation is successful.
  5. I am calling the "reject" function with the argument "they are not equal" if the operation is not successful.
  6. On line 19, I am calling the "then" method of the "promisDemo" obejct.
  7. "then" method again takes two function definitions as arguments. First one is the definition of the "resolve" function and the second one is the definition of "reject" function 
  8. If you change the value of variable "num2" to something other than 100, you should get the output of "they are not equal" since "reject" function is going to fire.
Now lets take this a step further and address the real challenge. First try it yourself and then com back to this solution.
Output:
At line 7, I have implemented a function which accepts the arguments as follows
  1. message : the message to print ("statement 01", "statement 02" and so on)
  2. thisDelay: how much time the current operation should take
  3. nextDelay: how much time the next process should be delayed 
Actually the argument 2 and 3 is only required for this example. In reality, you do not specify how much time the operations should be delayed. For example, and API call will take some time and that process will be delayed by its own. The promise is required to make sure that the next operation is not carried out before the current one. We only need these final 2 arguments only because we are simulating the delay with "setTimeout" function. 

Starting from line 20, these returned promises are chained together to get the desired result. 

Now, regardless of how much time an operation takes, the java interpreter executes them synchronously. 



Comments

Popular posts from this blog

Javascript 105 : Callbacks

Javascript is asynchronous. That means you cant guarantee that the code you write will always execute sequentially. Take the following code for example, Output When looking at the output, it is understandable that the statements has been executing sequentially.  But if I do a modification to the code like the following, the output will be different.  Output:  Don't worry about the line number 6 yet. the amendment there will just delay the the execution of the statement "console.log('statement 01')" by 100 milliseconds. Now the "statement 01" prints out at the end of the line. The change of the output can be explained as follows. the JS interpreter sees the line 6 (which is the first line of the script), and realize that it has to wait for a 100 milliseconds before executing the statement "console.log('statement 01')", but sees that other four lines has no such delay and can be executed right away. So it goes a...

Javascript 102 : Understanding 'this' keyword

The keyword "this" is frequently misunderstood when coding with Javascript. It is because its behavior depends on the execution context. Now what is "execution context"? It is mainly of three types. Global Execution Cotnext (GEC), Functional Execution Cotnext (FEC) and Eval. In GEC, it is the global environment which Javascript  (JS) is running. If you are running the script in a browser and you use the "this" keyword, it will refer to the "Window" object. But if you are using NodeJS and running the script outside a browser the "this" keyword would refer to the "Process". In FEC the "this" keyword would refer to the execution context created by the code inside the function. EVAL is hen you use the "this" keyword inside an "eval" function. If this does not make sense, don't worry because we are going to understand with an example which is always the best way. Make the following HT...