Promise

A promise is a JavaScript object that allows you to make asynchronous (aka async) calls. It produces a value when the async operation completes successfully or produces an error if it doesn’t complete. A promise may be in one of 3 possible states: fulfilled, rejected, or pending.

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

myResolve(); // when successful
myReject(); // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
)

 

  1. A “producing code” that does something and takes time. For instance, some code that loads the data over a network.
  2. A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result.
  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.