Categories
Javascript

JavaScript Promise - Basics

Promise

Promises are used to handle asynchronous operations in JavaScript
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Benefits of Promises
1- Improves Code Readability
2- Better handling of asynchronous operations
3- Better flow of control definition in asynchronous logic
4- Better Error Handling

A Promise has four states:
1-fulfilled: Action related to the promise succeeded
2-rejected: Action related to the promise failed
3- pending: Promise is still pending i.e not fulfilled or rejected yet
A promise can be created using Promise constructor.

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

Difference between Promise and Observables
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.

Observables
1-Emit multiple values over a period of time.
2-subscriptions that are cancellable using the unsubscribe() method

Promises
1-Emit a single value at a time, A promise can only handle one event
2-Are not cancellable.

Custom Promise

function cP(successCb,errorCb){
    setTimeout(()=>{
       let data ="ajay";
       if(data){
          successCb(data)
       } else{
          errorCb("no Data")
       }
    },2000)
}
cP((res)=>{console.log(res)},(er)=>{console.log(er)})