promise states code example

Example 1: promise states javascript

// A JavaScript Promise can be in several states:

// - Pending - response is not ready yet. Please wait.
// - Fulfilled - response is ready. Success. Take the data.
// - Rejected - an error occurred. Handle it.

Example 2: javascript promise

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example 3: .promise()

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});