What are promise in JavaScript? Explain with example

What is a promise?

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.

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.

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);
})
Share