Learn Angular From 0 to 100 — ES6 features — Part 3

Sukesh Marla
Apr 25 · 9 min read

Complete series source code can be downloaded from GitHub

Introduction

We are in the middle of our journey to Station 2 from Station 1.

Is Station 1, Station 2 these words confusing you? It means you are not following this series from the beginning.

This article is part of a series called “Learn Angular from 0 to 100”. We imagine this series as a train journey. Every time we reach a new station, we become competent into something.

So far, we have reached Station 1 and, on the way, to Station 2.

In this article, we will explore Promises in ES6.

Complete series

Promise

To understand “Promise” properly, first, we need to understand synchronous and asynchronous programming.

Instead of using complicated statements for understanding “Promise,” let’s do some coding.

First, let’s prepare all the ingredients needed for actual demos.

For all our demos, we will be needed a function that will run slow.

I took the following code from the internet to demonstrate the same. Do not worry much about it. Just remember that it’s slow and we have not created it, we are just going to invoke it.😉

Now assume that we have the following code.

In the above code, you can assume every “logic” to be some unique logic needed in the application.
For the demonstration purpose, let’s use “console.log” instead of comments.

The output will be quite straightforward.

Image for post
Image for post

So we are ready with all the needed ingredients. Let’s do our very first demo.

Demo 1 — Need for “callback.”

If you carefully examine the code, you can easily conclude that “logic 6” and “logic 7” is dependent on “logic 3,” whereas “logic 4” and “logic 5” are entirely independent of “logic 3”.

Image for post
Image for post

So, the point is why we should wait for 3 seconds to get the result of “logic 4” and “logic 5”.
The answer is, there is no reason. We should not wait for it.

It can be accomplished by making code inside “MyFunction” execute asynchronously. It can be done using JavaScript’s “setTimeout” function. “setTimeout” simply queues the code to run once the current call stack is finished executing. It merely breaks the normal synchronous flow.

Now the question is how to return the value from the “MyFunction” function?

That can be accomplished using “callback functions.”

“callback functions” are old and proven methodology to deal with asynchronous programming.

Here is the final code.

Let us understand the flow.

  • “Logic 1” runs, and the message is displayed on the screen.
  • “Logic 2” runs, and the message is displayed on the screen.
  • “Logic 3” runs, and it will make a call to “MyFunction.”
  • In “MyFunction,” “setTimeout” is used, which will queue logic inside it (that is a call to “SlowFunction”) to run only after the current call stack completes execution. In short, in this case, “MyFunction” executes and quickly finishes its execution.
  • Logic 4” runs, and the message is displayed on the screen.
  • “Logic 5” runs, and the message is displayed on the screen.
  • Now call stack is complete (all code execution completes), so queued code starts executing. It means 3 seconds wait, and then “callbackFn” is executed.
  • “Logic 6” runs, and the message is displayed on the screen.
  • “Logic 7” runs, and the message is displayed on the screen.
Image for post
Image for post

As you can see, now no need to wait for 3 seconds to get “Logic 4” and “Logic 5”.

So, that is why we need “callback functions.”

Demo 2 — Exceptions

Now, let’s say that “MyFunction” expects an even number as an input parameter. An odd number will be considered as invalid input. Now how to tackle it.

One will be like below.

Unlike static languages, In JavaScript, it’s not mandatory to return value from every part of the function. “MyFunction” has a simple “if..else” block, and in the “if” we are returning nothing, so “fnReturnValue” will have value as “undefined” whereas in “else,” we are returning a string value.

Although it works, it is not an exceptionally clean way. There is another more conventional approach, and that will be two “callback functions.” One for success and one for failure.

As you can see, we are passing two functions as an argument to “MyFunction.” One represents success, and one represents failure. It is a much cleaner approach than before.

Drawbacks of the above approach

  • There is no standard industry practice defining which function is a success, and which is a failure. For instance, in our case, success callback is expected before failure callback. You may find a different sequence in some other place.
  • Let’s say developers who created “MyFunction” make a logical mistake. He makes a call to “errorCallbackFn” immediately after “callbackFn.”

What will happen? Both will execute nothing else. 😊
Is it logical? The answer is No.
We can introduce other scenarios of logical mistakes as well, such as invoking “callbackFn” after “errorCallbackFn” or invoking “errorCallbackFn” more than once or invoking “callbackFn” more than once.
All these four points ultimately make insensible when we talk in terms of success and failure. Logically success and failure won’t be possible at the same time, and secondly, both success and failure should happen only once. Even if we invoke any of them multiple times, it should execute only once.

Demo 3 — “Callback hell.”

Let’s assume that we want to call multiple asynchronous methods one after the other. I mean, invoke one, and once that is over, make the call to another.

For the demo purpose, let’s try out with only three methods.

The above phenomenon is called “callback hell.”
Code becomes more and more complex and unreadable as more and more asynchronous methods are invoked.

Image for post
Image for post

Demo 4 — Promise
In Demo 1, we understood the importance of “callback.” We realized how much it is needed. Then in Demo 2 and Demo 3, we spoke about its limitations.
Let’s note down those limitations.

1. No standard way to identify success and failure.

2. “callback” leads to “callback hell” when the number of asynchronous methods is more.

“Promise” is the solution to these problems. It gives us the standard interface to deal with asynchronous methods.

Let’s do the demo and understand the same.

In the above code, we are creating an instance of “Promise” passing a “callback” as an argument with two parameters. First represents success and second failure. “resolve” and “reject” are just parameter names, it can be anything. The best thing is, the first one is success and the second one failure.

Let’s look at the invoking code.

As you know, “MyFunction” is returning the “Promise” object. Promise object gives us a method called “then,” which expects two “callback” functions. The first one will be “success,” and the second will be “failure.”

Image for post
Image for post

Execute it using “node” to get the following output.

Image for post
Image for post

Let’s test it once for error.

The output will be as follows.

Image for post
Image for post

Now let’s examine if “Promise” really solved those issues.

Success and Failure
Now we have a standard way to represent success and failure.

Is it success and failure?
Change MyFunction to follows.

Now test the code.

Execute it.

Image for post
Image for post

As you can see, “reject” simply ignored as “resolve” is invoked before that. It means once, succeeds, there is no failure.

  • I also recommend you try invoking “resolve” after “reject.” It will prove there is not a failure after success.
  • Try Invoking “resolve” multiple times, which will confirm that once you succeed, it cannot succeed again.
  • Finally, try “reject” numerous times. Every time you will see only one getting executed, which will prove that once failed, it cannot fail again.

So, we do have real success and failure here.

What about the “callback hell”?
Promise solves that issue as well. Check the below code.

The code is more straightforward and readable now.

Image for post
Image for post

Conclusion

In the next part of the series, we will see ES6 Modules, and with that, we will reach Station 2.

I hope you have enjoyed this writing.

Stay tuned and practice well. Please drop comments and clap. It helps us to stay motivated to write more such series.

You can check me out on twitter @sukeshmarla.

In case you are looking for customized mobile or web application development, exclusive technical Consultancy for architecting your project, and want to train your people in advanced technologies, you can visit my company Just Compile or contact SukeshMarla@Gmail.com for details.

JustCompile

Training, Consultancy , Development, Resourcing

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store