Explain Promise in Javascript?

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A Promise has four states:

fulfilled: Action related to the promise succeeded
rejected: Action related to the promise failed
pending: Promise is still pending i.e. not fulfilled or rejected yet
settled: Promise has fulfilled or rejected

A promise can be created using Promise constructor.


var promise = new Promise(function(resolve, reject){

     //do something


Promises can be consumed by registering functions using .then and .catch methods.

then() - then() is invoked when a promise is either resolved or rejected. It may also be defined as a career which takes data from promise and further executes it successfully.
Parameters - then() method takes two functions as parameters.

First function is executed if promise is resolved and a result is received.

Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method



        //handle success

    }, function(error){

        //handle error


catch() - catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters - catch() method takes one function as parameter.

Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )



        //handle error