javascript promise keyword code example

Example 1: 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 2: promise js

//example
function tetheredGetNumber(resolve, reject) {
  try {
    setTimeout( 
      function() {
        const randomInt = Date.now();
        const value = randomInt % 10;
        try { 
          if(value >= THRESHOLD_A) {
            throw new Error(`Too large: ${value}`);
          } 
        } catch(msg) {
            reject(`Error in callback ${msg}`); 
        }
      resolve(value);
      return;
    }, 500);
  } catch(err) {
    reject(`Error during setup: ${err}`);
  }
  return;
}