What are promises in JavaScript? Explain with example.

What is a promise?

A Promise is an object that represents the fulfillment or failure of an asynchronous operation.

Why do we need Promise?

  • Promise objects handle asynchronous operations
  • It provides the ability to write cleaner code by reducing the call-back hell
  • It allows errors to be passed down the chain and handled in one common place so that the layers of error handling can be easily avoided

What are the states of promise?

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected
  • fulfilled: meaning that the operation completed successfully
  • rejected: meaning that the operation failed
promise javascript
Credit: Mozilla

Example of promise:

let promiseToWriteReactApp = new Promise(function(resolve, reject){
   isWritten = true;
   (isWritten) ? resolve('resolved') : reject('rejected');
})

promiseToWriteReactApp.then(function(fromResolve){
   console.log(fromResolve);
}).catch(function(fromReject){
   console.log(fromReject);
})

Source:
Mozilla
JavaScript Info

Share