Keeping Promises using JavaScript – Part 1

Promises using JavaScript is not something new, it has been introduced years back, but we are not using because of not all the browsers didn’t support Promises at the time.

Before using Promises one should have clear idea about why need to use promises, as there any alternate apporaches to it etc. I seen lot of blog just giving a example to get started on promises before even explaning about basic asynchronous concept or even callbacks, which are related to JavaScript Promises. Below we are going to cover almost all concept involving around promises.

Life in Synchronous & Asynchronous Way!

Synchronous are things which are aligned over time, i.e one has response to the other and so on. For example, conversation is synchronous, dancing like that.

JavaScript, by default holds to things and do it one by one which we id this a “synchronous” (Except for few things like AJAX calls). Because JavaScript is single threaded and code will run one after an another.

Eventhough the working of ‘Synchronous’ can be useful for debugging; but it limits the thought of doing things multiple.

The problem with handling multiple things at the same time is “how to handle” the response? However, there are lot of other options to try.

Living with Callbacks!

Callbacks are nice way to acheive “asynchronous” way! Just a create a function, wrap the environment and pass it on, so it can be triggered somewhere else.

Example: simple callback

This is just a simple example, we can create even more complex callbacks. But there comes a problem with callbacks which are difficult to solve.

Example: Deep nesting A.K.A callback hell

{ function OnSuccess() { function DoThat() { …. } } function OnFailure() { function CallThis() { } } }

– Deep nesting
– Inconsistent callback behaviour
– Handling Errors
– Chaining

you read more about issues on callback from []

What about Events?

Similary like callback, events are great way to attach multiple times on a same object. Managing success and failure is still tricky!

Writing as Human Brain’s – Promises!

Promises – an asynchronous operation which provides great way to handle simulationous requests with precesion. They provide callbacks like functionality for each indiviual requests with more control both success and error data.

Promises exist to represent something that will be available in the future

Promises are very Promising because…

  • Code looks clean and more readable
  • Catching errors
  • Chaining
  • Multiple API calls &checking it simultaneously.

Solving the callback hell using Promises!

even better, chaining,

also, simultaneously run!

With JavaScript Promises, you can acheive the asynchorous way with ease and have more control over the data. In the part 2, we will some examples in action and also we need to know when to use Promises and when not to use it. Thats it for today! Enjoy!

Promises ain’t Callbacks; Its better!

  3. (for the image)