Understanding Promises in JavaScript : asynchronous behaviour of Javascript Part -2

In the previous article, we learned about using callback for performing asynchronous operations. In ES06/ES2015, Javascript introduced something called Promises which helps you handle  asynchronous operations in a better way The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a better way for managing asynchronous operations when compared to traditional callback-based way. Promises represent data that may not be available but will be available later upon completing some asynchronous operation. A promise can be called a placeholder for future data and  has 3 states PENDING RESOLVED REJECTED Immediately on creation, the state of a Promise is pending. Resolved state means the asynchronous operation is fulfilled. Rejected means that the asynchronous operation is not completed and has some errors. Many Javascript native apis for asynchronous operations support promises since ES06. Prior to that many libraries including JQuery and Bluebird were used to create promises for doing asynchronous operations. Example for promises JavaScript fetch method returns a promise.

You can see that immediately the state of promise is pending. Now for resolving the promise and getting the output Promise.prototype.then() and Promise.prototype.catch() Promise.prototype.then() and Promise.prototype.catch() The promise object has a then method that returns the promise…

Javascript try,catch and finally : Error handling
interview questions , Javascript / June 21, 2018

When we run Javascript code unexpected errors can happen but how to handle these errors… Handling the errors are necessary for providing a better end user experience and Javascript provides some features to efficiently handles the errors Try statement – Try statement checks for errors in a block of code. Consider the following code,the httpGet function send a Get request to a dummy api

This successfully runs , but what if we provide a wrong api url

  As you can see try and Catch Statement lets us handle errors while the code is being executed Throw Statement Throw statement lets us throw custom errors.The error thrown can be a string,number or an object Consider the following example

Here the request was successful but we expected a.userId to be 100.Since the result was not the expected one we throw a custom error.  ‘Not Expected Result’; Using the try and catch statements together, we can control the  program flow and generate custom error messages. Finally statement Finally statement ,lets us execute a block of code irrespecitve of the results of the try and catch.Consider the above example in which we throws a custom error.Now we add a finally…

Share this page in social media platforms